file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: UNLICENSED // Code from: https://github.com/kulkarohan/deposit pragma solidity 0.8.13; import { ERC20 } from "@rari-capital/solmate/src/tokens/ERC20.sol"; /// @title Deposit /// @author kulkarohan /// @notice Mock contract to transfer ERC-20 tokens with a signed approval contract EIP712 { /// /// /// EVENTS /// /// /// /// @notice Emitted after an ERC-20 token deposit /// @param user The depositooor /// @param tokenContract The token address /// @param amount The number of tokens deposited event TokenDeposit(address user, address tokenContract, uint256 amount); /// @notice Emitted after an ERC-20 token withdraw /// @param user The withdrawooor /// @param tokenContract The token address /// @param amount The number of tokens withdrawn event TokenWithdraw(address user, address tokenContract, uint256 amount); /// /// /// STORAGE /// /// /// /// @notice The number of tokens stored for a given user and token contract /// @dev User => ERC-20 address => Number of tokens deposited mapping(address => mapping(address => uint256)) public userDeposits; /// /// /// DEPOSIT /// /// /// /// @notice Deposits ERC-20 tokens (requires pre-approval) /// @param _tokenContract The ERC-20 token address /// @param _amount The number of tokens function deposit(address _tokenContract, uint256 _amount) external { ERC20(_tokenContract).transferFrom(msg.sender, address(this), _amount); userDeposits[msg.sender][_tokenContract] += _amount; emit TokenDeposit(msg.sender, _tokenContract, _amount); } /// /// /// DEPOSIT w/ PERMIT /// /// /// /// @notice Deposits ERC-20 tokens with a signed approval /// @param _tokenContract The ERC-20 token address /// @param _amount The number of tokens to transfer /// @param _owner The user signing the approval /// @param _spender The user to transfer the tokens (ie this contract) /// @param _value The number of tokens to appprove the spender /// @param _deadline The timestamp the permit expires /// @param _v The 129th byte and chain id of the signature /// @param _r The first 64 bytes of the signature /// @param _s Bytes 64-128 of the signature function depositWithPermit( address _tokenContract, uint256 _amount, address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external { ERC20(_tokenContract).permit( _owner, _spender, _value, _deadline, _v, _r, _s ); ERC20(_tokenContract).transferFrom(_owner, address(this), _amount); userDeposits[_owner][_tokenContract] += _amount; emit TokenDeposit(_owner, _tokenContract, _amount); } /// /// /// WITHDRAW /// /// /// /// @notice Withdraws deposited ERC-20 tokens /// @param _tokenContract The ERC-20 token address /// @param _amount The number of tokens function withdraw(address _tokenContract, uint256 _amount) external { require( _amount <= userDeposits[msg.sender][_tokenContract], "INVALID_WITHDRAW" ); userDeposits[msg.sender][_tokenContract] -= _amount; ERC20(_tokenContract).transfer(msg.sender, _amount); emit TokenWithdraw(msg.sender, _tokenContract, _amount); } }
Deposits ERC-20 tokens with a signed approval _tokenContract The ERC-20 token address _amount The number of tokens to transfer _owner The user signing the approval _spender The user to transfer the tokens (ie this contract) _value The number of tokens to appprove the spender _deadline The timestamp the permit expires _v The 129th byte and chain id of the signature _r The first 64 bytes of the signature _s Bytes 64-128 of the signature
function depositWithPermit( address _tokenContract, uint256 _amount, address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external { ERC20(_tokenContract).permit( _owner, _spender, _value, _deadline, _v, _r, _s ); ERC20(_tokenContract).transferFrom(_owner, address(this), _amount); userDeposits[_owner][_tokenContract] += _amount; emit TokenDeposit(_owner, _tokenContract, _amount); }
14,079,913
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /** * @title RLPEncode * @dev A simple RLP encoding library. * @author Bakaoh */ library RLPEncode { /* * Internal functions */ /** * @dev RLP encodes a byte string. * @param self The byte string to encode. * @return The RLP encoded string in bytes. */ function encodeBytes(bytes memory self) internal pure returns (bytes memory) { bytes memory encoded; if (self.length == 1 && uint8(self[0]) <= 128) { encoded = self; } else { encoded = concat(encodeLength(self.length, 128), self); } return encoded; } /** * @dev RLP encodes a list of RLP encoded byte byte strings. * @param self The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function encodeList(bytes[] memory self) internal pure returns (bytes memory) { bytes memory list = flatten(self); return concat(encodeLength(list.length, 192), list); } /** * @dev RLP encodes a string. * @param self The string to encode. * @return The RLP encoded string in bytes. */ function encodeString(string memory self) internal pure returns (bytes memory) { return encodeBytes(bytes(self)); } /** * @dev RLP encodes an address. * @param self The address to encode. * @return The RLP encoded address in bytes. */ function encodeAddress(address self) internal pure returns (bytes memory) { bytes memory inputBytes; assembly { let m := mload(0x40) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, self)) mstore(0x40, add(m, 52)) inputBytes := m } return encodeBytes(inputBytes); } /** * @dev RLP encodes a uint. * @param self The uint to encode. * @return The RLP encoded uint in bytes. */ function encodeUint(uint self) internal pure returns (bytes memory) { return encodeBytes(toBinary(self)); } /** * @dev RLP encodes an int. * @param self The int to encode. * @return The RLP encoded int in bytes. */ function encodeInt(int self) internal pure returns (bytes memory) { return encodeUint(uint(self)); } /** * @dev RLP encodes a bool. * @param self The bool to encode. * @return The RLP encoded bool in bytes. */ function encodeBool(bool self) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (self ? bytes1(0x01) : bytes1(0x80)); return encoded; } /* * Private functions */ /** * @dev Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param len The length of the string or the payload. * @param offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function encodeLength(uint len, uint offset) private pure returns (bytes memory) { bytes memory encoded; if (len < 56) { encoded = new bytes(1); encoded[0] = bytes32(len + offset)[31]; } else { uint lenLen; uint i = 1; while (len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = bytes32(lenLen + offset + 55)[31]; for(i = 1; i <= lenLen; i++) { encoded[i] = bytes32((len / (256**(lenLen-i))) % 256)[31]; } } return encoded; } /** * @dev Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function toBinary(uint _x) private pure returns (bytes memory) { bytes memory b = new bytes(32); assembly { mstore(add(b, 32), _x) } uint i; for (i = 0; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * @dev Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function memcpy(uint _dest, uint _src, uint _len) private pure { uint dest = _dest; uint src = _src; uint len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * @dev Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint len; uint i; for (i = 0; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint listPtr; assembly { listPtr := add(item, 0x20)} memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } /** * @dev Concatenates two bytes. * @notice From: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol. * @param _preBytes First byte string. * @param _postBytes Second byte string. * @return Both byte string combined. */ function concat(bytes memory _preBytes, bytes memory _postBytes) private pure returns (bytes memory) { bytes memory tempBytes; assembly { tempBytes := mload(0x40) let length := mload(_preBytes) mstore(tempBytes, length) let mc := add(tempBytes, 0x20) let end := add(mc, length) for { let cc := add(_preBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) mc := end end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) )) } return tempBytes; } } /** * SPDX-License-Identifier: MIT */ pragma solidity ^0.8.0; import "./MultiSigWallet.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; contract MultiSigCloneFactory { address public multiSigImplementation; event ContractCreated(address contractAddress, string typeName); constructor(address _multSigImplementation) { multiSigImplementation = _multSigImplementation; } /*function create(address owner) public returns (address) { address payable instance = payable(Clones.clone(multiSigImplementation)); MultiSigWallet(instance).initialize(owner); emit ContractCreated(instance, "MultiSigWallet"); return instance; }*/ function predict(bytes32 salt) external view returns (address) { return Clones.predictDeterministicAddress(multiSigImplementation, salt); } function create(address owner, bytes32 salt) external returns (address) { address payable instance = payable(Clones.cloneDeterministic(multiSigImplementation, salt)); MultiSigWallet(instance).initialize(owner); emit ContractCreated(instance, "MultiSigWallet"); return instance; } } /** * SPDX-License-Identifier: MIT */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../libraries/RLPEncode.sol"; import "../utils/Nonce.sol"; contract MultiSigWallet is Nonce, Initializable { mapping (address => uint8) public signers; // The addresses that can co-sign transactions and the number of signatures needed uint16 public signerCount; bytes public contractId; // most likely unique id of this contract event SignerChange( address indexed signer, uint8 cosignaturesNeeded ); event Transacted( address indexed toAddress, // The address the transaction was sent to bytes4 selector, // selected operation address[] signers // Addresses of the signers used to initiate the transaction ); constructor () { } function initialize(address owner) external initializer { // We use the gas price to get a unique id into our transactions. // Note that 32 bits do not guarantee that no one can generate a contract with the // same id, but it practically rules out that someone accidentally creates two // two multisig contracts with the same id, and that's all we need to prevent // replay-attacks. contractId = toBytes(uint32(uint160(address(this)))); _setSigner(owner, 1); // set initial owner } /** * It should be possible to store ether on this address. */ receive() external payable { } /** * Checks if the provided signatures suffice to sign the transaction and if the nonce is correct. */ function checkSignatures(uint128 nonce, address to, uint value, bytes calldata data, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) external view returns (address[] memory) { bytes32 transactionHash = calculateTransactionHash(nonce, contractId, to, value, data); return verifySignatures(transactionHash, v, r, s); } /** * Checks if the execution of a transaction would succeed if it was properly signed. */ function checkExecution(address to, uint value, bytes calldata data) external { Address.functionCallWithValue(to, data, value); require(false, "Test passed. Reverting."); } function execute(uint128 nonce, address to, uint value, bytes calldata data, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) external returns (bytes memory) { bytes32 transactionHash = calculateTransactionHash(nonce, contractId, to, value, data); address[] memory found = verifySignatures(transactionHash, v, r, s); bytes memory returndata = Address.functionCallWithValue(to, data, value); flagUsed(nonce); emit Transacted(to, extractSelector(data), found); return returndata; } function extractSelector(bytes calldata data) private pure returns (bytes4){ if (data.length < 4){ return bytes4(0); } else { return bytes4(data[0]) | (bytes4(data[1]) >> 8) | (bytes4(data[2]) >> 16) | (bytes4(data[3]) >> 24); } } function toBytes(uint number) internal pure returns (bytes memory){ uint len = 0; uint temp = 1; while (number >= temp){ temp = temp << 8; len++; } temp = number; bytes memory data = new bytes(len); for (uint i = len; i>0; i--) { data[i-1] = bytes1(uint8(temp)); temp = temp >> 8; } return data; } // Note: does not work with contract creation function calculateTransactionHash(uint128 sequence, bytes memory id, address to, uint value, bytes calldata data) internal view returns (bytes32){ bytes[] memory all = new bytes[](9); all[0] = toBytes(sequence); // sequence number instead of nonce all[1] = id; // contract id instead of gas price all[2] = toBytes(21000); // gas limit all[3] = abi.encodePacked(to); all[4] = toBytes(value); all[5] = data; all[6] = toBytes(block.chainid); all[7] = toBytes(0); for (uint i = 0; i<8; i++){ all[i] = RLPEncode.encodeBytes(all[i]); } all[8] = all[7]; return keccak256(RLPEncode.encodeList(all)); } function verifySignatures(bytes32 transactionHash, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) public view returns (address[] memory) { address[] memory found = new address[](r.length); for (uint i = 0; i < r.length; i++) { address signer = ecrecover(transactionHash, v[i], r[i], s[i]); uint8 cosignaturesNeeded = signers[signer]; require(cosignaturesNeeded > 0 && cosignaturesNeeded <= r.length, "cosigner error"); found[i] = signer; } requireNoDuplicates(found); return found; } function requireNoDuplicates(address[] memory found) private pure { for (uint i = 0; i < found.length; i++) { for (uint j = i+1; j < found.length; j++) { require(found[i] != found[j], "duplicate signature"); } } } /** * Call this method through execute */ function setSigner(address signer, uint8 cosignaturesNeeded) external authorized { _setSigner(signer, cosignaturesNeeded); require(signerCount > 0); } function migrate(address destination) external { _migrate(msg.sender, destination); } function migrate(address source, address destination) external authorized { _migrate(source, destination); } function _migrate(address source, address destination) private { require(signers[destination] == 0); // do not overwrite existing signer! _setSigner(destination, signers[source]); _setSigner(source, 0); } function _setSigner(address signer, uint8 cosignaturesNeeded) private { require(!Address.isContract(signer), "signer cannot be a contract"); uint8 prevValue = signers[signer]; signers[signer] = cosignaturesNeeded; if (prevValue > 0 && cosignaturesNeeded == 0){ signerCount--; } else if (prevValue == 0 && cosignaturesNeeded > 0){ signerCount++; } emit SignerChange(signer, cosignaturesNeeded); } modifier authorized() { require(address(this) == msg.sender || signers[msg.sender] == 1, "not authorized"); _; } } /** * SPDX-License-Identifier: LicenseRef-Aktionariat * * MIT License with Automated License Fee Payments * * Copyright (c) 2020 Aktionariat AG (aktionariat.com) * * Permission is hereby granted 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. * - All automated license fee payments integrated into this and related Software * are preserved. * * 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.8.0; contract Nonce { uint256 public constant MAX_INCREASE = 100; uint256 private compound; constructor(){ setBoth(128, 0); } /** * The next recommended nonce, which is the highest nonce ever used plus one. */ function nextNonce() external view returns (uint256){ return getMax() + 1; } /** * Returns whether the provided nonce can be used. * For the 100 nonces in the interval [nextNonce(), nextNonce + 99], this is always true. * For the nonces in the interval [nextNonce() - 129, nextNonce() - 1], this is true for the nonces that have not been used yet. */ function isFree(uint128 nonce) external view returns (bool){ uint128 max = getMax(); return isValidHighNonce(max, nonce) || isValidLowNonce(max, getRegister(), nonce); } /** * Flags the given nonce as used. * Reverts if the provided nonce is not free. */ function flagUsed(uint128 nonce) internal { uint256 comp = compound; uint128 max = uint128(comp); uint128 reg = uint128(comp >> 128); if (isValidHighNonce(max, nonce)){ setBoth(nonce, ((reg << 1) | 0x1) << (nonce - max - 1)); } else if (isValidLowNonce(max, reg, nonce)){ setBoth(max, uint128(reg | 0x1 << (max - nonce - 1))); } else { require(false); } } function getMax() private view returns (uint128) { return uint128(compound); } function getRegister() private view returns (uint128) { return uint128(compound >> 128); } function setBoth(uint128 max, uint128 reg) private { compound = uint256(reg) << 128 | max; } function isValidHighNonce(uint128 max, uint128 nonce) private pure returns (bool){ return nonce > max && nonce <= max + MAX_INCREASE; } function isValidLowNonce(uint128 max, uint128 reg, uint256 nonce) private pure returns (bool){ uint256 diff = max - nonce; return diff > 0 && diff <= 128 && ((0x1 << (diff - 1)) & reg == 0); } }
RLP encodes a string. self The string to encode. return The RLP encoded string in bytes./
function encodeString(string memory self) internal pure returns (bytes memory) { return encodeBytes(bytes(self)); }
383,602
./full_match/1/0x204FD7979db82941a8Db7d770cb70B7b5B5e9A3A/sources/contracts/vault/Vault.sol
Inherit from IVault receive fees from seller and buyer receive offering assets recieve consideration assets
function receiveAssets( TradeDetailed calldata trade, Fees calldata buyerFees, Fees calldata sellerFees ) external override onlyCore returns (bool) { if (buyerFees.amount > 0) _transferFees(buyerFees, trade.buyer); if (sellerFees.amount > 0) _transferFees(sellerFees, trade.seller); _receiveAssets(trade.offeringAssets, trade.seller); _receiveAssets(trade.considerationAssets, trade.buyer); return true; }
16,536,785
pragma solidity 0.4.18; /// @title Math operations with safety checks library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(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) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function 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; } function toPower2(uint256 a) internal pure returns (uint256) { return mul(a, a); } function sqrt(uint256 a) internal pure returns (uint256) { uint256 c = (a + 1) / 2; uint256 b = a; while (c < b) { b = c; c = (a / c + c) / 2; } return b; } } /// @title ERC223Receiver Interface /// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223 contract ERC223Receiver { function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok); } /// @title Market Maker Interface. /// @author Tal Beja. contract MarketMaker is ERC223Receiver { function getCurrentPrice() public constant returns (uint _price); function change(address _fromToken, uint _amount, address _toToken) public returns (uint _returnAmount); function change(address _fromToken, uint _amount, address _toToken, uint _minReturn) public returns (uint _returnAmount); function change(address _toToken) public returns (uint _returnAmount); function change(address _toToken, uint _minReturn) public returns (uint _returnAmount); function quote(address _fromToken, uint _amount, address _toToken) public constant returns (uint _returnAmount); function openForPublicTrade() public returns (bool success); function isOpenForPublic() public returns (bool success); event Change(address indexed fromToken, uint inAmount, address indexed toToken, uint returnAmount, address indexed account); } /// @title Ellipse Market Maker Interfase /// @author Tal Beja contract IEllipseMarketMaker is MarketMaker { // precision for price representation (as in ether or tokens). uint256 public constant PRECISION = 10 ** 18; // The tokens pair. ERC20 public token1; ERC20 public token2; // The tokens reserves. uint256 public R1; uint256 public R2; // The tokens full suplly. uint256 public S1; uint256 public S2; // State flags. bool public operational; bool public openForPublic; // Library contract address. address public mmLib; function supportsToken(address token) public constant returns (bool); function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256); function validateReserves() public view returns (bool); function withdrawExcessReserves() public returns (uint256); function initializeAfterTransfer() public returns (bool); function initializeOnTransfer() public returns (bool); function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256); } /// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20) contract ERC20 { uint public totalSupply; function balanceOf(address _owner) constant public returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /// @title Ownable /// @dev The Ownable contract has an owner address, and provides basic authorization control functions, /// this simplifies the implementation of "user permissions". /// @dev Based on OpenZeppelin's Ownable. contract Ownable { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed _by, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); /// @dev Constructor sets the original `owner` of the contract to the sender account. function Ownable() public { owner = msg.sender; } /// @dev Reverts if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyOwnerCandidate() { require(msg.sender == newOwnerCandidate); _; } /// @dev Proposes to transfer control of the contract to a newOwnerCandidate. /// @param _newOwnerCandidate address The address to transfer ownership to. function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { require(_newOwnerCandidate != address(0)); newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } /// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner. function acceptOwnership() external onlyOwnerCandidate { address previousOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = address(0); OwnershipTransferred(previousOwner, owner); } } /// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier contract Standard223Receiver is ERC223Receiver { Tkn tkn; struct Tkn { address addr; address sender; // the transaction caller uint256 value; } bool __isTokenFallback; modifier tokenPayable { require(__isTokenFallback); _; } /// @dev Called when the receiver of transfer is contract /// @param _sender address the address of tokens sender /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) { if (!supportsToken(msg.sender)) { return false; } // Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory. // Solution: Remove the the data tkn = Tkn(msg.sender, _sender, _value); __isTokenFallback = true; if (!address(this).delegatecall(_data)) { __isTokenFallback = false; return false; } // avoid doing an overwrite to .token, which would be more expensive // makes accessing .tkn values outside tokenPayable functions unsafe __isTokenFallback = false; return true; } function supportsToken(address token) public constant returns (bool); } /// @title TokenOwnable /// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation contract TokenOwnable is Standard223Receiver, Ownable { /// @dev Reverts if called by any account other than the owner for token sending. modifier onlyTokenOwner() { require(tkn.sender == owner); _; } } /// @title Ellipse Market Maker Library. /// @dev market maker, using ellipse equation. /// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf /// @author Tal Beja. contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker { using SafeMath for uint256; // temp reserves uint256 private l_R1; uint256 private l_R2; modifier notConstructed() { require(mmLib == address(0)); _; } /// @dev Reverts if not operational modifier isOperational() { require(operational); _; } /// @dev Reverts if operational modifier notOperational() { require(!operational); _; } /// @dev Reverts if msg.sender can't trade modifier canTrade() { require(openForPublic || msg.sender == owner); _; } /// @dev Reverts if tkn.sender can't trade modifier canTrade223() { require (openForPublic || tkn.sender == owner); _; } /// @dev The Market Maker constructor /// @param _mmLib address address of the market making lib contract /// @param _token1 address contract of the first token for marker making (CLN) /// @param _token2 address contract of the second token for marker making (CC) function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) { require(_mmLib != address(0)); require(_token1 != address(0)); require(_token2 != address(0)); require(_token1 != _token2); mmLib = _mmLib; token1 = ERC20(_token1); token2 = ERC20(_token2); R1 = 0; R2 = 0; S1 = token1.totalSupply(); S2 = token2.totalSupply(); operational = false; openForPublic = false; return true; } /// @dev open the Market Maker for public trade. function openForPublicTrade() public onlyOwner isOperational returns (bool) { openForPublic = true; return true; } /// @dev returns true iff the contract is open for public trade. function isOpenForPublic() public onlyOwner returns (bool) { return (openForPublic && operational); } /// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls) /// @param _token address adress of the contract to check function supportsToken(address _token) public constant returns (bool) { return (token1 == _token || token2 == _token); } /// @dev initialize the contract after transfering all of the tokens form the pair function initializeAfterTransfer() public notOperational onlyOwner returns (bool) { require(initialize()); return true; } /// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) { require(initialize()); return true; } /// @dev initialize the contract. function initialize() private returns (bool success) { R1 = token1.balanceOf(this); R2 = token2.balanceOf(this); // one reserve should be full and the second should be empty success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1)); if (success) { operational = true; } } /// @dev the price of token1 in terms of token2, represented in 18 decimals. function getCurrentPrice() public constant isOperational returns (uint256) { return getPrice(R1, R2, S1, S2); } /// @dev the price of token1 in terms of token2, represented in 18 decimals. /// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2 /// @param _R1 uint256 reserve of the first token /// @param _R2 uint256 reserve of the second token /// @param _S1 uint256 total supply of the first token /// @param _S2 uint256 total supply of the second token function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) { price = PRECISION; price = price.mul(_S1.sub(_R1)); price = price.div(_S2.sub(_R2)); price = price.mul(_S2); price = price.div(_S1); price = price.mul(_S2); price = price.div(_S1); } /// @dev get a quote for exchanging and update temporary reserves. /// @param _fromToken the token to sell from /// @param _inAmount the amount to sell /// @param _toToken the token to buy /// @return the return amount of the buying token function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) { // if buying token2 from token1 if (token1 == _fromToken && token2 == _toToken) { // add buying amount to the temp reserve l_R1 = R1.add(_inAmount); // calculate the other reserve l_R2 = calcReserve(l_R1, S1, S2); if (l_R2 > R2) { return 0; } // the returnAmount is the other reserve difference returnAmount = R2.sub(l_R2); } // if buying token1 from token2 else if (token2 == _fromToken && token1 == _toToken) { // add buying amount to the temp reserve l_R2 = R2.add(_inAmount); // calculate the other reserve l_R1 = calcReserve(l_R2, S2, S1); if (l_R1 > R1) { return 0; } // the returnAmount is the other reserve difference returnAmount = R1.sub(l_R1); } else { return 0; } } /// @dev get a quote for exchanging. /// @param _fromToken the token to sell from /// @param _inAmount the amount to sell /// @param _toToken the token to buy /// @return the return amount of the buying token function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) { uint256 _R1; uint256 _R2; // if buying token2 from token1 if (token1 == _fromToken && token2 == _toToken) { // add buying amount to the temp reserve _R1 = R1.add(_inAmount); // calculate the other reserve _R2 = calcReserve(_R1, S1, S2); if (_R2 > R2) { return 0; } // the returnAmount is the other reserve difference returnAmount = R2.sub(_R2); } // if buying token1 from token2 else if (token2 == _fromToken && token1 == _toToken) { // add buying amount to the temp reserve _R2 = R2.add(_inAmount); // calculate the other reserve _R1 = calcReserve(_R2, S2, S1); if (_R1 > R1) { return 0; } // the returnAmount is the other reserve difference returnAmount = R1.sub(_R1); } else { return 0; } } /// @dev calculate second reserve from the first reserve and the supllies. /// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1 /// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve /// @param _R1 the first reserve /// @param _S1 the first total supply /// @param _S2 the second total supply /// @return _R2 the second reserve function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) { _R2 = _S2 .mul( _S1 .sub( _R1 .mul(_S1) .mul(2) .sub( _R1 .toPower2() ) .sqrt() ) ) .div(_S1); } /// @dev change tokens. /// @param _fromToken the token to sell from /// @param _inAmount the amount to sell /// @param _toToken the token to buy /// @return the return amount of the buying token function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) { return change(_fromToken, _inAmount, _toToken, 0); } /// @dev change tokens. /// @param _fromToken the token to sell from /// @param _inAmount the amount to sell /// @param _toToken the token to buy /// @param _minReturn the munimum token to buy /// @return the return amount of the buying token function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) { // pull transfer the selling token require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount)); // exchange the token returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn); if (returnAmount == 0) { // if no return value revert revert(); } // transfer the buying token ERC20(_toToken).transfer(msg.sender, returnAmount); // validate the reserves require(validateReserves()); Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender); } /// @dev change tokens using erc223\erc677 transfer. /// @param _toToken the token to buy /// @return the return amount of the buying token function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) { return change(_toToken, 0); } /// @dev change tokens using erc223\erc677 transfer. /// @param _toToken the token to buy /// @param _minReturn the munimum token to buy /// @return the return amount of the buying token function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) { // get from token and in amount from the tkn object address fromToken = tkn.addr; uint256 inAmount = tkn.value; // exchange the token returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn); if (returnAmount == 0) { // if no return value revert revert(); } // transfer the buying token ERC20(_toToken).transfer(tkn.sender, returnAmount); // validate the reserves require(validateReserves()); Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender); } /// @dev exchange tokens. /// @param _fromToken the token to sell from /// @param _inAmount the amount to sell /// @param _toToken the token to buy /// @param _minReturn the munimum token to buy /// @return the return amount of the buying token function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) { // get quote and update temp reserves returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken); // if the return amount is lower than minimum return, don't buy if (returnAmount == 0 || returnAmount < _minReturn) { return 0; } // update reserves from temp values updateReserve(); } /// @dev update token reserves from temp values function updateReserve() private { R1 = l_R1; R2 = l_R2; } /// @dev validate that the tokens balances don't goes below reserves function validateReserves() public view returns (bool) { return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2); } /// @dev allow admin to withraw excess tokens accumulated due to precision function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) { // if there is excess of token 1, transfer it to the owner if (token1.balanceOf(this) > R1) { returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1)); token1.transfer(msg.sender, token1.balanceOf(this).sub(R1)); } // if there is excess of token 2, transfer it to the owner if (token2.balanceOf(this) > R2) { returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2)); token2.transfer(msg.sender, token2.balanceOf(this).sub(R2)); } } }
update token reserves from temp values
function updateReserve() private { R1 = l_R1; R2 = l_R2; }
12,717,837
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271Upgradeable { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/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.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721URIStorage_init_unchained(); } function __ERC721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library 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; 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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSAUpgradeable.sol"; import "../AddressUpgradeable.sol"; import "../../interfaces/IERC1271Upgradeable.sol"; /** * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and * ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with * smart contract wallets such as Argent and Gnosis. * * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change * through time. It could return true at block N and false at block N+1 (or the opposite). * * _Available since v4.1._ */ library SignatureCheckerUpgradeable { function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSAUpgradeable.RecoverError error) = ECDSAUpgradeable.tryRecover(hash, signature); if (error == ECDSAUpgradeable.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271Upgradeable.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271Upgradeable.isValidSignature.selector); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title INiftyForge721 /// @author Simon Fremaux (@dievardump) interface INiftyForge721 { struct ModuleInit { address module; bool enabled; bool minter; } /// @notice totalSupply access function totalSupply() external view returns (uint256); /// @notice helper to know if everyone can mint or only minters function isMintingOpenToAll() external view returns (bool); /// @notice Toggle minting open to all state /// @param isOpen if the new state is open or not function setMintingOpenToAll(bool isOpen) external; /// @notice Mint token to `to` with `uri` /// @param to address of recipient /// @param uri token metadata uri /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transferring it to a recipient /// @return tokenId the tokenId function mint( address to, string memory uri, address feeRecipient, uint256 feeAmount, address transferTo ) external returns (uint256 tokenId); /// @notice Mint batch tokens to `to[i]` with `uri[i]` /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, address[] memory feeRecipients, uint256[] memory feeAmounts ) external returns (uint256[] memory tokenIds); /// @notice Mint `tokenId` to to` with `uri` /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it is doing. /// this also means, this function does not verify _maxTokenId /// @param to address of recipient /// @param uri token metadata uri /// @param tokenId token id wanted /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transferring it to a recipient /// @return tokenId the tokenId function mint( address to, string memory uri, uint256 tokenId_, address feeRecipient, uint256 feeAmount, address transferTo ) external returns (uint256 tokenId); /// @notice Mint batch tokens to `to[i]` with `uris[i]` /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it's doing. /// this also means, this function does not verify _maxTokenId /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param tokenIds array of token ids wanted /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, uint256[] memory tokenIds, address[] memory feeRecipients, uint256[] memory feeAmounts ) external returns (uint256[] memory); /// @notice Attach a module /// @param module a module to attach /// @param enabled if the module is enabled by default /// @param canModuleMint if the module has to be given the minter role function attachModule( address module, bool enabled, bool canModuleMint ) external; /// @dev Allows owner to enable a module /// @param module to enable /// @param canModuleMint if the module has to be given the minter role function enableModule(address module, bool canModuleMint) external; /// @dev Allows owner to disable a module /// @param module to disable function disableModule(address module, bool keepListeners) external; /// @notice function that returns a string that can be used to render the current token /// @param tokenId tokenId /// @return the URI to render token function renderTokenURI(uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import './ERC721Ownable.sol'; import './ERC721WithRoles.sol'; import './ERC721WithRoyalties.sol'; import './ERC721WithPermit.sol'; import './ERC721WithMutableURI.sol'; /// @title ERC721Full /// @dev This contains all the different overrides needed on /// ERC721 / URIStorage / Royalties /// This contract does not use ERC721enumerable because Enumerable adds quite some /// gas to minting costs and I am trying to make this cheap for creators. /// Also, since all NiftyForge contracts will be fully indexed in TheGraph it will easily /// Be possible to get tokenIds of an owner off-chain, before passing them to a contract /// which can verify ownership at the processing time /// @author Simon Fremaux (@dievardump) abstract contract ERC721Full is ERC721Ownable, ERC721BurnableUpgradeable, ERC721URIStorageUpgradeable, ERC721WithRoles, ERC721WithRoyalties, ERC721WithPermit, ERC721WithMutableURI { bytes32 public constant ROLE_EDITOR = keccak256('EDITOR'); bytes32 public constant ROLE_MINTER = keccak256('MINTER'); // base token uri string public baseURI; /// @notice modifier allowing only safe listed addresses to mint /// safeListed addresses have roles Minter, Editor or Owner modifier onlyMinter(address minter) virtual { require(canMint(minter), '!NOT_MINTER!'); _; } /// @notice only editor modifier onlyEditor(address sender) virtual override { require(canEdit(sender), '!NOT_EDITOR!'); _; } /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer) function __ERC721Full_init( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_ ) internal { __ERC721Ownable_init( name_, symbol_, contractURI_, openseaProxyRegistry_, owner_ ); __ERC721WithPermit_init(name_); } // receive() external payable {} /// @notice This is a generic function that allows this contract's owner to withdraw /// any balance / ERC20 / ERC721 / ERC1155 it can have /// this contract has no payable nor receive function so it should not get any nativ token /// but this could save some ERC20, 721 or 1155 /// @param token the token to withdraw from. address(0) means native chain token /// @param amount the amount to withdraw if native token, erc20 or erc1155 - must be 0 for ERC721 /// @param tokenId the tokenId to withdraw for ERC1155 and ERC721 function withdraw( address token, uint256 amount, uint256 tokenId ) external onlyOwner { if (token == address(0)) { require( amount == 0 || address(this).balance >= amount, '!WRONG_VALUE!' ); (bool success, ) = msg.sender.call{value: amount}(''); require(success, '!TRANSFER_FAILED!'); } else { // if token is ERC1155 if ( IERC165Upgradeable(token).supportsInterface( type(IERC1155Upgradeable).interfaceId ) ) { IERC1155Upgradeable(token).safeTransferFrom( address(this), msg.sender, tokenId, amount, '' ); } else if ( IERC165Upgradeable(token).supportsInterface( type(IERC721Upgradeable).interfaceId ) ) { //else if ERC721 IERC721Upgradeable(token).safeTransferFrom( address(this), msg.sender, tokenId, '' ); } else { // we consider it's an ERC20 require( IERC20Upgradeable(token).transfer(msg.sender, amount), '!TRANSFER_FAILED!' ); } } } /// @inheritdoc ERC165Upgradeable function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { // all moved here to have less "jumps" when checking an interface return interfaceId == type(IERC721WithMutableURI).interfaceId || interfaceId == type(IERC2981Royalties).interfaceId || interfaceId == type(IRaribleSecondarySales).interfaceId || interfaceId == type(IFoundationSecondarySales).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc ERC721Ownable function isApprovedForAll(address owner_, address operator) public view override(ERC721Upgradeable, ERC721Ownable) returns (bool) { return super.isApprovedForAll(owner_, operator); } /// @inheritdoc ERC721URIStorageUpgradeable function tokenURI(uint256 tokenId) public view virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } /// @notice Helper to know if an address can do the action an Editor can /// @param user the address to check function canEdit(address user) public view virtual returns (bool) { return isEditor(user) || owner() == user; } /// @notice Helper to know if an address can do the action an Editor can /// @param user the address to check function canMint(address user) public view virtual returns (bool) { return isMinter(user) || canEdit(user); } /// @notice Helper to know if an address is editor /// @param user the address to check function isEditor(address user) public view returns (bool) { return hasRole(ROLE_EDITOR, user); } /// @notice Helper to know if an address is minter /// @param user the address to check function isMinter(address user) public view returns (bool) { return hasRole(ROLE_MINTER, user); } /// @notice Allows to get approved using a permit and transfer in the same call /// @dev this supposes that the permit is for msg.sender /// @param from current owner /// @param to recipient /// @param tokenId the token id /// @param _data optional data to add /// @param deadline the deadline for the permit to be used /// @param signature of permit function safeTransferFromWithPermit( address from, address to, uint256 tokenId, bytes memory _data, uint256 deadline, bytes memory signature ) external { // use the permit to get msg.sender approved permit(msg.sender, tokenId, deadline, signature); // do the transfer safeTransferFrom(from, to, tokenId, _data); } /// @notice Set the base token URI /// @dev only an editor can do that (account or module) /// @param baseURI_ the new base token uri used in tokenURI() function setBaseURI(string memory baseURI_) external onlyEditor(msg.sender) { baseURI = baseURI_; } /// @notice Set the base mutable meta URI for tokens /// @param baseMutableURI_ the new base for mutable meta uri used in mutableURI() function setBaseMutableURI(string memory baseMutableURI_) external onlyEditor(msg.sender) { _setBaseMutableURI(baseMutableURI_); } /// @notice Set the mutable URI for a token /// @dev Mutable URI work like tokenURI /// -> if there is a baseMutableURI and a mutableURI, concat baseMutableURI + mutableURI /// -> else if there is only mutableURI, return mutableURI //. -> else if there is only baseMutableURI, concat baseMutableURI + tokenId /// @dev only an editor (account or module) can call this /// @param tokenId the token to set the mutable URI for /// @param mutableURI_ the mutable URI function setMutableURI(uint256 tokenId, string memory mutableURI_) external onlyEditor(msg.sender) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); _setMutableURI(tokenId, mutableURI_); } /// @notice Helper for the owner to add new editors /// @dev needs to be owner /// @param users list of new editors function addEditors(address[] memory users) public onlyOwner { for (uint256 i; i < users.length; i++) { _grantRole(ROLE_MINTER, users[i]); } } /// @notice Helper for the owner to remove editors /// @dev needs to be owner /// @param users list of removed editors function removeEditors(address[] memory users) public onlyOwner { for (uint256 i; i < users.length; i++) { _revokeRole(ROLE_MINTER, users[i]); } } /// @notice Helper for an editor to add new minter /// @dev needs to be owner /// @param users list of new minters function addMinters(address[] memory users) public onlyEditor(msg.sender) { for (uint256 i; i < users.length; i++) { _grantRole(ROLE_MINTER, users[i]); } } /// @notice Helper for an editor to remove minters /// @dev needs to be owner /// @param users list of removed minters function removeMinters(address[] memory users) public onlyEditor(msg.sender) { for (uint256 i; i < users.length; i++) { _revokeRole(ROLE_MINTER, users[i]); } } /// @notice Allows to change the default royalties recipient /// @dev an editor can call this /// @param recipient new default royalties recipient function setDefaultRoyaltiesRecipient(address recipient) external onlyEditor(msg.sender) { require(!hasPerTokenRoyalties(), '!PER_TOKEN_ROYALTIES!'); _setDefaultRoyaltiesRecipient(recipient); } /// @notice Allows a royalty recipient of a token to change their recipient address /// @dev only the current token royalty recipient can change the address /// @param tokenId the token to change the recipient for /// @param recipient new default royalties recipient function setTokenRoyaltiesRecipient(uint256 tokenId, address recipient) external { require(hasPerTokenRoyalties(), '!CONTRACT_WIDE_ROYALTIES!'); (address currentRecipient, ) = _getTokenRoyalty(tokenId); require(msg.sender == currentRecipient, '!NOT_ALLOWED!'); _setTokenRoyaltiesRecipient(tokenId, recipient); } /// @inheritdoc ERC721Upgradeable function _transfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721WithPermit) { super._transfer(from, to, tokenId); } /// @inheritdoc ERC721Upgradeable function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { // remove royalties _removeRoyalty(tokenId); // remove mutableURI _setMutableURI(tokenId, ''); // burn ERC721URIStorage super._burn(tokenId); } /// @inheritdoc ERC721Upgradeable function _baseURI() internal view virtual override returns (string memory) { return baseURI; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '../OpenSea/BaseOpenSea.sol'; /// @title ERC721Ownable /// @author Simon Fremaux (@dievardump) contract ERC721Ownable is OwnableUpgradeable, ERC721Upgradeable, BaseOpenSea { /// @notice modifier that allows higher level contracts to define /// editors that are not only the owner modifier onlyEditor(address sender) virtual { require(sender == owner(), '!NOT_EDITOR!'); _; } /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer) function __ERC721Ownable_init( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_ ) internal initializer { __Ownable_init(); __ERC721_init_unchained(name_, symbol_); // set contract uri if present if (bytes(contractURI_).length > 0) { _setContractURI(contractURI_); } // set OpenSea proxyRegistry for gas-less trading if present if (address(0) != openseaProxyRegistry_) { _setOpenSeaRegistry(openseaProxyRegistry_); } // transferOwnership if needed if (address(0) != owner_) { transferOwnership(owner_); } } /// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user /// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy /// @inheritdoc ERC721Upgradeable function isApprovedForAll(address owner_, address operator) public view virtual override returns (bool) { // allows gas less trading on OpenSea return super.isApprovedForAll(owner_, operator) || isOwnersOpenSeaProxy(owner_, operator); } /// @notice Helper for the owner of the contract to set the new contract URI /// @dev needs to be owner /// @param contractURI_ new contract URI function setContractURI(string memory contractURI_) external onlyEditor(msg.sender) { _setContractURI(contractURI_); } /// @notice Helper for the owner to set OpenSea's proxy (allowing or not gas-less trading) /// @dev needs to be owner /// @param osProxyRegistry new opensea proxy registry function setOpenSeaRegistry(address osProxyRegistry) external onlyEditor(msg.sender) { _setOpenSeaRegistry(osProxyRegistry); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol'; import './IERC721WithMutableURI.sol'; /// @dev This is a contract used to add mutableURI to the contract /// @author Simon Fremaux (@dievardump) contract ERC721WithMutableURI is IERC721WithMutableURI, ERC721Upgradeable { using StringsUpgradeable for uint256; // base mutable meta URI string public baseMutableURI; mapping(uint256 => string) private _tokensMutableURIs; /// @notice See {ERC721WithMutableURI-mutableURI}. function mutableURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); string memory _tokenMutableURI = _tokensMutableURIs[tokenId]; string memory base = _baseMutableURI(); // If both are set, concatenate the baseURI and mutableURI (via abi.encodePacked). if (bytes(base).length > 0 && bytes(_tokenMutableURI).length > 0) { return string(abi.encodePacked(base, _tokenMutableURI)); } // If only token mutable URI is set if (bytes(_tokenMutableURI).length > 0) { return _tokenMutableURI; } // else return base + tokenId return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ''; } /// @dev helper to get the base for mutable meta /// @return the base for mutable meta uri function _baseMutableURI() internal view returns (string memory) { return baseMutableURI; } /// @dev Set the base mutable meta URI /// @param baseMutableURI_ the new base for mutable meta uri used in mutableURI() function _setBaseMutableURI(string memory baseMutableURI_) internal { baseMutableURI = baseMutableURI_; } /// @dev Set the mutable URI for a token /// @param tokenId the token id /// @param mutableURI_ the new mutableURI for tokenId function _setMutableURI(uint256 tokenId, string memory mutableURI_) internal { if (bytes(mutableURI_).length == 0) { if (bytes(_tokensMutableURIs[tokenId]).length > 0) { delete _tokensMutableURIs[tokenId]; } } else { _tokensMutableURIs[tokenId] = mutableURI_; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/SignatureCheckerUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; /// @title ERC721WithPermit /// @author Simon Fremaux (@dievardump) /// @notice This implementation differs from what I can see everywhere else /// My take on Permits for NFTs is that the nonce should be linked to the tokens /// and not to an owner. /// Whenever a token is transfered, its nonce should increase. /// This allows to emit a lot of Permit (for sales for example) but ensure they /// will get invalidated after the token is transfered /// This also allows an owner to emit several Permit on different tokens /// and not have Permit to be used one after the other /// Example: /// An owner sign a Permit of sale on OpenSea and on Rarible at the same time /// Only the first one that will sell the item will be able to use the permit /// The nonce being incremented, this Permits won't be usable anymore abstract contract ERC721WithPermit is ERC721Upgradeable { bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)' ); bytes32 public DOMAIN_SEPARATOR; mapping(uint256 => uint256) private _nonces; // function to initialize the contract function __ERC721WithPermit_init(string memory name_) internal { DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(name_)), keccak256(bytes('1')), block.chainid, address(this) ) ); } /// @notice Allows to retrieve current nonce for token /// @param tokenId token id /// @return current nonce function nonce(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); return _nonces[tokenId]; } function makePermitDigest( address spender, uint256 tokenId, uint256 nonce_, uint256 deadline ) public view returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash( DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, spender, tokenId, nonce_, deadline ) ) ); } /// @notice function to be called by anyone to approve `spender` using a Permit signature /// @dev Anyone can call this to approve `spender`, even a third-party /// @param spender the actor to approve /// @param tokenId the token id /// @param deadline the deadline for the permit to be used /// @param signature permit function permit( address spender, uint256 tokenId, uint256 deadline, bytes memory signature ) public { require(deadline >= block.timestamp, '!PERMIT_DEADLINE_EXPIRED!'); // this will revert if token is burned address owner_ = ownerOf(tokenId); bytes32 digest = makePermitDigest( spender, tokenId, _nonces[tokenId], deadline ); (address recoveredAddress, ) = ECDSAUpgradeable.tryRecover( digest, signature ); require( ( // no need to check for recoveredAddress == 0 // because if it's 0, it won't work (recoveredAddress == owner_ || isApprovedForAll(owner_, recoveredAddress)) ) || // if owner is a contract, try to recover signature using SignatureChecker SignatureCheckerUpgradeable.isValidSignatureNow( owner_, digest, signature ), '!INVALID_PERMIT_SIGNATURE!' ); _approve(spender, tokenId); } /// @dev helper to easily increment a nonce for a given tokenId /// @param tokenId the tokenId to increment the nonce for function _incrementNonce(uint256 tokenId) internal { _nonces[tokenId]++; } /// @dev _transfer override to be able to increment the nonce /// @inheritdoc ERC721Upgradeable function _transfer( address from, address to, uint256 tokenId ) internal virtual override { super._transfer(from, to, tokenId); // increment the permit nonce linked to this tokenId. // this will ensure that a Permit can not be used on a token // if it were to leave the owner's hands and come back later // this if saves 20k on the mint, which is already expensive enough if (from != address(0)) { _incrementNonce(tokenId); } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol'; /// @title ERC721WithRoles /// @author Simon Fremaux (@dievardump) abstract contract ERC721WithRoles { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /// @notice emitted when a role is given to a user /// @param role the granted role /// @param user the user that got a role granted event RoleGranted(bytes32 indexed role, address indexed user); /// @notice emitted when a role is givrevoked from a user /// @param role the revoked role /// @param user the user that got a role revoked event RoleRevoked(bytes32 indexed role, address indexed user); mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /// @notice Helper to know is an address has a role /// @param role the role to check /// @param user the address to check function hasRole(bytes32 role, address user) public view returns (bool) { return _roleMembers[role].contains(user); } /// @notice Helper to list all users in a role /// @return list of role members function listRole(bytes32 role) external view returns (address[] memory list) { uint256 count = _roleMembers[role].length(); list = new address[](count); for (uint256 i; i < count; i++) { list[i] = _roleMembers[role].at(i); } } /// @notice internal helper to grant a role to a user /// @param role role to grant /// @param user to grant role to function _grantRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].add(user)) { emit RoleGranted(role, user); return true; } return false; } /// @notice Helper to revoke a role from a user /// @param role role to revoke /// @param user to revoke role from function _revokeRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].remove(user)) { emit RoleRevoked(role, user); return true; } return false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '../Royalties/ERC2981/ERC2981Royalties.sol'; import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol'; import '../Royalties/FoundationSecondarySales/IFoundationSecondarySales.sol'; /// @dev This is a contract used for royalties on various platforms /// @author Simon Fremaux (@dievardump) contract ERC721WithRoyalties is ERC2981Royalties, IRaribleSecondarySales, IFoundationSecondarySales { /// @inheritdoc IRaribleSecondarySales function getFeeRecipients(uint256 tokenId) public view override returns (address payable[] memory recipients) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); } } /// @inheritdoc IRaribleSecondarySales function getFeeBps(uint256 tokenId) public view override returns (uint256[] memory fees) { // using ERC2981 implementation to get the amount (, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { fees = new uint256[](1); fees[0] = amount; } } function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory recipients, uint256[] memory fees) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); fees = new uint256[](1); fees[0] = amount; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @dev This is the interface for NFT extension mutableURI /// @author Simon Fremaux (@dievardump) interface IERC721WithMutableURI { function mutableURI(uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's /// gas-less trading and contractURI support contract BaseOpenSea { event NewContractURI(string contractURI); string private _contractURI; address private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Returns the current OS proxyRegistry address registered function proxyRegistry() public view returns (address) { return _proxyRegistry; } /// @notice Helper allowing OpenSea gas-less trading by verifying who's operator /// for owner /// @dev Allows to check if `operator` is owner's OpenSea proxy on eth mainnet / rinkeby /// or to check if operator is OpenSea's proxy contract on Polygon and Mumbai /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { address proxyRegistry_ = _proxyRegistry; // if we have a proxy registry if (proxyRegistry_ != address(0)) { // on ethereum mainnet or rinkeby use "ProxyRegistry" to // get owner's proxy if (block.chainid == 1 || block.chainid == 4) { return address(ProxyRegistry(proxyRegistry_).proxies(owner)) == operator; } else if (block.chainid == 137 || block.chainid == 80001) { // on Polygon and Mumbai just try with OpenSea's proxy contract // https://docs.opensea.io/docs/polygon-basic-integration return proxyRegistry_ == operator; } } return false; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; emit NewContractURI(contractURI_); } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = proxyRegistryAddress; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './IERC2981Royalties.sol'; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 abstract contract ERC2981Royalties is IERC2981Royalties { struct RoyaltyData { address recipient; uint96 amount; } // this variable is set to true, whenever "contract wide" royalties are set // this can not be undone and this takes precedence to any other royalties already set. bool private _useContractRoyalties; // those are the "contract wide" royalties, used for collections that all pay royalties to // the same recipient, with the same value // once set, like any other royalties, it can not be modified RoyaltyData private _contractRoyalties; mapping(uint256 => RoyaltyData) private _royalties; function hasPerTokenRoyalties() public view returns (bool) { return !_useContractRoyalties; } /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256 tokenId, uint256 value) public view override returns (address receiver, uint256 royaltyAmount) { // get base values (receiver, royaltyAmount) = _getTokenRoyalty(tokenId); // calculate due amount if (royaltyAmount != 0) { royaltyAmount = (value * royaltyAmount) / 10000; } } /// @dev Sets token royalties /// @param id the token id fir which we register the royalties function _removeRoyalty(uint256 id) internal { delete _royalties[id]; } /// @dev Sets token royalties /// @param id the token id for which we register the royalties /// @param recipient recipient of the royalties /// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setTokenRoyalty( uint256 id, address recipient, uint256 value ) internal { // you can't set per token royalties if using "contract wide" ones require( !_useContractRoyalties, '!ERC2981Royalties:ROYALTIES_CONTRACT_WIDE!' ); require(value <= 10000, '!ERC2981Royalties:TOO_HIGH!'); _royalties[id] = RoyaltyData(recipient, uint96(value)); } /// @dev Gets token royalties /// @param id the token id for which we check the royalties function _getTokenRoyalty(uint256 id) internal view virtual returns (address, uint256) { RoyaltyData memory data; if (_useContractRoyalties) { data = _contractRoyalties; } else { data = _royalties[id]; } return (data.recipient, uint256(data.amount)); } /// @dev set contract royalties; /// This can only be set once, because we are of the idea that royalties /// Amounts should never change after they have been set /// Once default values are set, it will be used for all royalties inquiries /// @param recipient the default royalties recipient /// @param value the default royalties value function _setDefaultRoyalties(address recipient, uint256 value) internal { require( _useContractRoyalties == false, '!ERC2981Royalties:DEFAULT_ALREADY_SET!' ); require(value <= 10000, '!ERC2981Royalties:TOO_HIGH!'); _useContractRoyalties = true; _contractRoyalties = RoyaltyData(recipient, uint96(value)); } /// @dev allows to set the default royalties recipient /// @param recipient the new recipient function _setDefaultRoyaltiesRecipient(address recipient) internal { _contractRoyalties.recipient = recipient; } /// @dev allows to set a tokenId royalties recipient /// @param tokenId the token Id /// @param recipient the new recipient function _setTokenRoyaltiesRecipient(uint256 tokenId, address recipient) internal { _royalties[tokenId].recipient = recipient; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; interface IFoundationSecondarySales { /// @notice returns a list of royalties recipients and the amount /// @param tokenId the token Id to check for /// @return all the recipients and their basis points, for tokenId function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; interface IRaribleSecondarySales { /// @notice returns a list of royalties recipients /// @param tokenId the token Id to check for /// @return all the recipients for tokenId function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); /// @notice returns a list of royalties amounts /// @param tokenId the token Id to check for /// @return all the amounts for tokenId function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './Modules/INFModuleWithEvents.sol'; /// @title INiftyForgeBase /// @author Simon Fremaux (@dievardump) interface INiftyForgeModules { enum ModuleStatus { UNKNOWN, ENABLED, DISABLED } /// @notice Helper to list all modules with their state /// @return list of modules and status function listModules() external view returns (address[] memory list, uint256[] memory status); /// @notice allows a module to listen to events (mint, transfer, burn) /// @param eventType the type of event to listen to function addEventListener(INFModuleWithEvents.Events eventType) external; /// @notice allows a module to stop listening to events (mint, transfer, burn) /// @param eventType the type of event to stop listen to function removeEventListener(INFModuleWithEvents.Events eventType) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol'; interface INFModule is IERC165Upgradeable { /// @notice Called by a Token Registry whenever the module is Attached /// @return if the attach worked function onAttach() external returns (bool); /// @notice Called by a Token Registry whenever the module is Enabled /// @return if the enabling worked function onEnable() external returns (bool); /// @notice Called by a Token Registry whenever the module is Disabled function onDisable() external; /// @notice returns an URI with information about the module /// @return the URI where to find information about the module function contractURI() external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleMutableURI is INFModule { function mutableURI(uint256 tokenId) external view returns (string memory); function mutableURI(address registry, uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleRenderTokenURI is INFModule { function renderTokenURI(uint256 tokenId) external view returns (string memory); function renderTokenURI(address registry, uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleTokenURI is INFModule { function tokenURI(uint256 tokenId) external view returns (string memory); function tokenURI(address registry, uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleWithEvents is INFModule { enum Events { MINT, TRANSFER, BURN } /// @dev callback received from a contract when an event happens /// @param eventType the type of event fired /// @param tokenId the token for which the id is fired /// @param from address from /// @param to address to function onEvent( Events eventType, uint256 tokenId, address from, address to ) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleWithRoyalties is INFModule { /// @notice Return royalties (recipient, basisPoint) for tokenId /// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters /// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible) /// @param tokenId token to check /// @return recipient and basisPoint for this tokenId function royaltyInfo(uint256 tokenId) external view returns (address recipient, uint256 basisPoint); /// @notice Return royalties (recipient, basisPoint) for tokenId /// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters /// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible) /// @param registry registry to check id of /// @param tokenId token to check /// @return recipient and basisPoint for this tokenId function royaltyInfo(address registry, uint256 tokenId) external view returns (address recipient, uint256 basisPoint); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol'; import './Modules/INFModule.sol'; import './Modules/INFModuleWithEvents.sol'; import './INiftyForgeModules.sol'; /// @title NiftyForgeBase /// @author Simon Fremaux (@dievardump) /// @notice These modules can be attached to a contract and enabled/disabled later /// They can be used to mint elements (need Minter Role) but also can listen /// To events like MINT, TRANSFER and BURN /// /// To module developers: /// Remember cross contract calls have a high cost, and reads too. /// Do not abuse of Events and only use them if there is a high value to it /// Gas is not cheap, always think of users first. contract NiftyForgeModules is INiftyForgeModules { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // event emitted whenever a module status changed event ModuleChanged(address module); // 3 types of events Mint, Transfer and Burn EnumerableSetUpgradeable.AddressSet[3] private _listeners; // modules list // should create a module role instead? EnumerableSetUpgradeable.AddressSet internal modules; // modules status mapping(address => ModuleStatus) public modulesStatus; modifier onlyEnabledModule() { require( modulesStatus[msg.sender] == ModuleStatus.ENABLED, '!MODULE_NOT_ENABLED!' ); _; } /// @notice Helper to list all modules with their state /// @return list of modules and status function listModules() external view override returns (address[] memory list, uint256[] memory status) { uint256 count = modules.length(); list = new address[](count); status = new uint256[](count); for (uint256 i; i < count; i++) { list[i] = modules.at(i); status[i] = uint256(modulesStatus[list[i]]); } } /// @notice allows a module to listen to events (mint, transfer, burn) /// @param eventType the type of event to listen to function addEventListener(INFModuleWithEvents.Events eventType) external override onlyEnabledModule { _listeners[uint256(eventType)].add(msg.sender); } /// @notice allows a module to stop listening to events (mint, transfer, burn) /// @param eventType the type of event to stop listen to function removeEventListener(INFModuleWithEvents.Events eventType) external override onlyEnabledModule { _listeners[uint256(eventType)].remove(msg.sender); } /// @notice Attach a module /// @param module a module to attach /// @param enabled if the module is enabled by default function _attachModule(address module, bool enabled) internal { require( modulesStatus[module] == ModuleStatus.UNKNOWN, '!ALREADY_ATTACHED!' ); // add to modules list modules.add(module); // tell the module it's attached // making sure module can be attached to this contract require(INFModule(module).onAttach(), '!ATTACH_FAILED!'); if (enabled) { _enableModule(module); } else { _disableModule(module, true); } } /// @dev Allows owner to enable a module (needs to be disabled) /// @param module to enable function _enableModule(address module) internal { require( modulesStatus[module] != ModuleStatus.ENABLED, '!NOT_DISABLED!' ); modulesStatus[module] = ModuleStatus.ENABLED; // making sure module can be enabled on this contract require(INFModule(module).onEnable(), '!ENABLING_FAILED!'); emit ModuleChanged(module); } /// @dev Disables a module /// @param module the module to disable /// @param keepListeners a boolean to know if the module can still listen to events /// meaning the module can not interact with the contract anymore but is still working /// for example: a module that transfers an ERC20 to people Minting function _disableModule(address module, bool keepListeners) internal virtual { require( modulesStatus[module] != ModuleStatus.DISABLED, '!NOT_ENABLED!' ); modulesStatus[module] = ModuleStatus.DISABLED; // we do a try catch without checking return or error here // because owners should be able to disable a module any time without the module being ok // with it or not try INFModule(module).onDisable() {} catch {} // remove all listeners if not explicitely asked to keep them if (!keepListeners) { _listeners[uint256(INFModuleWithEvents.Events.MINT)].remove(module); _listeners[uint256(INFModuleWithEvents.Events.TRANSFER)].remove( module ); _listeners[uint256(INFModuleWithEvents.Events.BURN)].remove(module); } emit ModuleChanged(module); } /// @dev fire events to listeners /// @param eventType the type of event fired /// @param tokenId the token for which the id is fired /// @param from address from /// @param to address to function _fireEvent( INFModuleWithEvents.Events eventType, uint256 tokenId, address from, address to ) internal { EnumerableSetUpgradeable.AddressSet storage listeners = _listeners[ uint256(eventType) ]; uint256 length = listeners.length(); for (uint256 i; i < length; i++) { INFModuleWithEvents(listeners.at(i)).onEvent( eventType, tokenId, from, to ); } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './NFT/ERC721Helpers/ERC721Full.sol'; import './NiftyForge/Modules/INFModuleWithEvents.sol'; import './NiftyForge/Modules/INFModuleTokenURI.sol'; import './NiftyForge/Modules/INFModuleRenderTokenURI.sol'; import './NiftyForge/Modules/INFModuleWithRoyalties.sol'; import './NiftyForge/Modules/INFModuleMutableURI.sol'; import './NiftyForge/NiftyForgeModules.sol'; import './INiftyForge721.sol'; /// @title NiftyForge721 /// @author Simon Fremaux (@dievardump) contract NiftyForge721 is INiftyForge721, NiftyForgeModules, ERC721Full { /// @dev This contains the last token id that was created uint256 public lastTokenId; uint256 public totalSupply; bool private _mintingOpenToAll; // this can be set only once by the owner of the contract // this is used to ensure a max token creation that can be used // for example when people create a series of XX elements // since this contract works with "Minters", it is good to // be able to set in it that there is a max number of elements // and that this can not change uint256 public maxTokenId; mapping(uint256 => address) public tokenIdToModule; /// @notice modifier allowing only safe listed addresses to mint /// safeListed addresses have roles Minter, Editor or Owner modifier onlyMinter(address minter) virtual override { require(isMintingOpenToAll() || canMint(minter), '!NOT_MINTER!'); _; } /// @notice this is the constructor of the contract, called at the time of creation /// Although it uses what are called upgradeable contracts, this is only to /// be able to make deployment cheap using a Proxy but NiftyForge contracts /// ARE NOT UPGRADEABLE => the proxy used is not an upgradeable proxy, the implementation is immutable /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership /// @param modulesInit_ modules to add / enable directly at creation /// @param contractRoyaltiesRecipient the recipient, if the contract has "contract wide royalties" /// @param contractRoyaltiesValue the value, modules to add / enable directly at creation function initialize( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_, ModuleInit[] memory modulesInit_, address contractRoyaltiesRecipient, uint256 contractRoyaltiesValue ) external initializer { __ERC721Full_init( name_, symbol_, contractURI_, openseaProxyRegistry_, owner_ ); for (uint256 i; i < modulesInit_.length; i++) { _attachModule(modulesInit_[i].module, modulesInit_[i].enabled); if (modulesInit_[i].enabled && modulesInit_[i].minter) { _grantRole(ROLE_MINTER, modulesInit_[i].module); } } // here, if contractRoyaltiesRecipient is not address(0) but // contractRoyaltiesValue is 0, this will mean that this contract will // NEVER have royalties, because whenever default royalties are set, it is // always used for every tokens. if ( contractRoyaltiesRecipient != address(0) || contractRoyaltiesValue != 0 ) { _setDefaultRoyalties( contractRoyaltiesRecipient, contractRoyaltiesValue ); } } /// @notice helper to know if everyone can mint or only minters function isMintingOpenToAll() public view override returns (bool) { return _mintingOpenToAll; } /// @notice returns a tokenURI /// @dev This function will first check if there is a tokenURI registered for this token in the contract /// if not it will check if the token comes from a Module, and if yes, try to get the tokenURI from it /// /// @param tokenId a parameter just like in doxygen (must be followed by parameter name) /// @return uri the tokenURI /// @inheritdoc ERC721Upgradeable function tokenURI(uint256 tokenId) public view virtual override returns (string memory uri) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); // first, try to get the URI from the module that might have created it (bool support, address module) = _moduleSupports( tokenId, type(INFModuleTokenURI).interfaceId ); if (support) { uri = INFModuleTokenURI(module).tokenURI(tokenId); } // if uri not set, get it with the normal tokenURI if (bytes(uri).length == 0) { uri = super.tokenURI(tokenId); } } /// @notice function that returns a string that can be used to render the current token /// this can be an URL but also any other data uri /// This is something that I would like to present as an EIP later to allow dynamique /// render URL /// @param tokenId tokenId /// @return uri the URI to render token function renderTokenURI(uint256 tokenId) public view override returns (string memory uri) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); // Try to get the URI from the module that might have created this token (bool support, address module) = _moduleSupports( tokenId, type(INFModuleRenderTokenURI).interfaceId ); if (support) { uri = INFModuleRenderTokenURI(module).renderTokenURI(tokenId); } } /// @notice Toggle minting open to all state /// @param isOpen if the new state is open or not function setMintingOpenToAll(bool isOpen) external override onlyEditor(msg.sender) { _mintingOpenToAll = isOpen; } /// @notice allows owner to set maxTokenId /// @dev be careful, this is a one time call function. /// When set, the maxTokenId can not be reverted nor changed /// @param maxTokenId_ the max token id possible function setMaxTokenId(uint256 maxTokenId_) external onlyEditor(msg.sender) { require(maxTokenId == 0, '!MAX_TOKEN_ALREADY_SET!'); maxTokenId = maxTokenId_; } /// @notice function that returns a string that can be used to add metadata on top of what is in tokenURI /// This function has been added because sometimes, we want some metadata to be completly immutable /// But to have others that aren't (for example if a token is linked to a physical token, and the physical /// token state can change over time) /// This way we can reflect those changes without risking breaking the base meta (tokenURI) /// @param tokenId tokenId /// @return uri the URI where mutable can be found function mutableURI(uint256 tokenId) public view override returns (string memory uri) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); // first, try to get the URI from the module that might have created it (bool support, address module) = _moduleSupports( tokenId, type(INFModuleMutableURI).interfaceId ); if (support) { uri = INFModuleMutableURI(module).mutableURI(tokenId); } // if uri not set, get it with the normal mutableURI if (bytes(uri).length == 0) { uri = super.mutableURI(tokenId); } } /// @notice Mint token to `to` with `uri` /// @param to address of recipient /// @param uri token metadata uri /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transfering it to a recipient /// @return tokenId the tokenId function mint( address to, string memory uri, address feeRecipient, uint256 feeAmount, address transferTo ) public override onlyMinter(msg.sender) returns (uint256 tokenId) { tokenId = lastTokenId + 1; lastTokenId = mint( to, uri, tokenId, feeRecipient, feeAmount, transferTo ); } /// @notice Mint batch tokens to `to[i]` with `uri[i]` /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, address[] memory feeRecipients, uint256[] memory feeAmounts ) public override onlyMinter(msg.sender) returns (uint256[] memory tokenIds) { require( to.length == uris.length && to.length == feeRecipients.length && to.length == feeAmounts.length, '!LENGTH_MISMATCH!' ); uint256 tokenId = lastTokenId; tokenIds = new uint256[](to.length); // verify that we don't overflow // done here instead of in _mint so we do one read // instead of to.length _verifyMaxTokenId(tokenId + to.length); bool isModule = modulesStatus[msg.sender] == ModuleStatus.ENABLED; for (uint256 i; i < to.length; i++) { tokenId++; _mint( to[i], uris[i], tokenId, feeRecipients[i], feeAmounts[i], isModule ); tokenIds[i] = tokenId; } // setting lastTokenId after will ensure that any reEntrancy will fail // to mint, because the minting will throw with a duplicate id lastTokenId = tokenId; } /// @notice Mint `tokenId` to to` with `uri` and transfer to transferTo if not null /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it is doing. /// this also means, this function does not verify maxTokenId /// @param to address of recipient /// @param uri token metadata uri /// @param tokenId_ token id wanted /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transfering it to a recipient /// @return the tokenId function mint( address to, string memory uri, uint256 tokenId_, address feeRecipient, uint256 feeAmount, address transferTo ) public override onlyMinter(msg.sender) returns (uint256) { // minting will throw if the tokenId_ already exists // we also verify maxTokenId in this case // because else it would allow owners to mint arbitrary tokens // after setting the max _verifyMaxTokenId(tokenId_); _mint( to, uri, tokenId_, feeRecipient, feeAmount, modulesStatus[msg.sender] == ModuleStatus.ENABLED ); if (transferTo != address(0)) { _transfer(to, transferTo, tokenId_); } return tokenId_; } /// @notice Mint batch tokens to `to[i]` with `uris[i]` /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it's doing. /// this also means, this function does not verify maxTokenId /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param tokenIds array of token ids wanted /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, uint256[] memory tokenIds, address[] memory feeRecipients, uint256[] memory feeAmounts ) public override onlyMinter(msg.sender) returns (uint256[] memory) { // minting will throw if any tokenIds[i] already exists require( to.length == uris.length && to.length == tokenIds.length && to.length == feeRecipients.length && to.length == feeAmounts.length, '!LENGTH_MISMATCH!' ); uint256 highestId; for (uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] > highestId) { highestId = tokenIds[i]; } } // we also verify maxTokenId in this case // because else it would allow owners to mint arbitrary tokens // after setting the max _verifyMaxTokenId(highestId); bool isModule = modulesStatus[msg.sender] == ModuleStatus.ENABLED; for (uint256 i; i < to.length; i++) { if (tokenIds[i] > highestId) { highestId = tokenIds[i]; } _mint( to[i], uris[i], tokenIds[i], feeRecipients[i], feeAmounts[i], isModule ); } return tokenIds; } /// @notice Attach a module /// @param module a module to attach /// @param enabled if the module is enabled by default /// @param moduleCanMint if the module has to be given the minter role function attachModule( address module, bool enabled, bool moduleCanMint ) external override onlyEditor(msg.sender) { // give the minter role if enabled and moduleCanMint if (moduleCanMint && enabled) { _grantRole(ROLE_MINTER, module); } _attachModule(module, enabled); } /// @dev Allows owner to enable a module /// @param module to enable /// @param moduleCanMint if the module has to be given the minter role function enableModule(address module, bool moduleCanMint) external override onlyEditor(msg.sender) { // give the minter role if moduleCanMint if (moduleCanMint) { _grantRole(ROLE_MINTER, module); } _enableModule(module); } /// @dev Allows owner to disable a module /// @param module to disable function disableModule(address module, bool keepListeners) external override onlyEditor(msg.sender) { _disableModule(module, keepListeners); } /// @dev Internal mint function /// @param to token recipient /// @param uri token uri /// @param tokenId token Id /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amounts. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param isModule if the minter is a module function _mint( address to, string memory uri, uint256 tokenId, address feeRecipient, uint256 feeAmount, bool isModule ) internal { _safeMint(to, tokenId, ''); if (bytes(uri).length > 0) { _setTokenURI(tokenId, uri); } if (feeAmount > 0) { _setTokenRoyalty(tokenId, feeRecipient, feeAmount); } if (isModule) { tokenIdToModule[tokenId] = msg.sender; } } // here we override _mint, _transfer and _burn because we want the event to be fired // only after the action is done // else we would have done that in _beforeTokenTransfer /// @dev _mint override to be able to fire events /// @inheritdoc ERC721Upgradeable function _mint(address to, uint256 tokenId) internal virtual override { super._mint(to, tokenId); totalSupply++; _fireEvent(INFModuleWithEvents.Events.MINT, tokenId, address(0), to); } /// @dev _transfer override to be able to fire events /// @inheritdoc ERC721Upgradeable function _transfer( address from, address to, uint256 tokenId ) internal virtual override { super._transfer(from, to, tokenId); if (to == address(0xdEaD)) { _fireEvent(INFModuleWithEvents.Events.BURN, tokenId, from, to); } else { _fireEvent(INFModuleWithEvents.Events.TRANSFER, tokenId, from, to); } } /// @dev _burn override to be able to fire event /// @inheritdoc ERC721Upgradeable function _burn(uint256 tokenId) internal virtual override { address owner_ = ownerOf(tokenId); super._burn(tokenId); totalSupply--; _fireEvent( INFModuleWithEvents.Events.BURN, tokenId, owner_, address(0) ); } function _disableModule(address module, bool keepListeners) internal override { // always revoke the minter role when disabling a module _revokeRole(ROLE_MINTER, module); super._disableModule(module, keepListeners); } /// @dev Verifies that we do not create more token ids than the max if set /// @param tokenId the tokenId to verify function _verifyMaxTokenId(uint256 tokenId) internal view { uint256 maxTokenId_ = maxTokenId; require(maxTokenId_ == 0 || tokenId <= maxTokenId_, '!MAX_TOKEN_ID!'); } /// @dev Gets token royalties taking modules into account /// @param tokenId the token id for which we check the royalties function _getTokenRoyalty(uint256 tokenId) internal view override returns (address royaltyRecipient, uint256 royaltyAmount) { (royaltyRecipient, royaltyAmount) = super._getTokenRoyalty(tokenId); // if there are no royalties set either contract wide or per token if (royaltyAmount == 0) { // try to see if the token was created by a module that manages royalties (bool support, address module) = _moduleSupports( tokenId, type(INFModuleWithRoyalties).interfaceId ); if (support) { (royaltyRecipient, royaltyAmount) = INFModuleWithRoyalties( module ).royaltyInfo(tokenId); } } } function _moduleSupports(uint256 tokenId, bytes4 interfaceId) internal view returns (bool support, address module) { module = tokenIdToModule[tokenId]; support = module != address(0) && IERC165Upgradeable(module).supportsInterface(interfaceId); } }
Allows to retrieve current nonce for token tokenId token id return current nonce
function nonce(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); return _nonces[tokenId]; }
1,626,352
./full_match/5/0xa571ADD7eb84314899b44E2087Bf3c4a0A137efA/sources/contracts/DNFTwilight.sol
See {ERC721-_transferFrom}.
function transferFrom( address from, address to, uint256 tokenId ) public override onlyAllowedOperator(from) { super.transferFrom(from, to, tokenId); }
1,856,121
pragma solidity 0.4.24; /** * @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; } } //import "openzeppelin-eth/contracts/ownership/Ownable.sol"; //pragma solidity ^0.4.24; //import "zos-lib/contracts/Initializable.sol"; //pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable { address private _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. */ function initialize(address sender) public initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit 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; } uint256[50] private ______gap; } //import "openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol"; //pragma solidity ^0.4.24; //import "./IERC20.sol"; //pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } //import "./lib/SafeMathInt.sol"; /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //pragma solidity 0.4.24; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } /** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */ contract UFragments is ERC20Detailed, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); // Used for authentication address public monetaryPolicy; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } bool private rebasePausedDeprecated; bool private tokenPausedDeprecated; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 50 * 10**6 * 10**DECIMALS; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); // From this point forward, _gonsPerFragment is taken as the source of truth. // We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment // conversion rate. // This means our applied supplyDelta can deviate from the requested supplyDelta, // but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply). // // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is // ever increased, it must be re-included. // _totalSupply = TOTAL_GONS.div(_gonsPerFragment) emit LogRebase(epoch, _totalSupply); return _totalSupply; } function initialize(address owner_) public initializer { ERC20Detailed.initialize("AmpleForthGold", "AAU", uint8(DECIMALS)); Ownable.initialize(owner_); rebasePausedDeprecated = false; tokenPausedDeprecated = false; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonBalances[owner_] = TOTAL_GONS; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit Transfer(address(0x0), owner_, _totalSupply); } /** * @return The total number of fragments. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view returns (uint256) { return _gonBalances[who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[from] = _gonBalances[from].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @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) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } } //import "./RebaseDelta.sol"; //pragma solidity >=0.4.24; //import '@uniswap/v2-periphery/contracts/libraries/SafeMath.sol'; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library RB_SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } function div(uint x, uint y) internal pure returns (uint) { require(y != 0); return x / y; } } library RB_UnsignedSafeMath { function add(int x, int y) internal pure returns (int z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(int x, int y) internal pure returns (int z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(int x, int y) internal pure returns (int z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } function div(int x, int y) internal pure returns (int) { require(y != 0); return x / y; } } //import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; 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; } /** Calculates the Delta for a rebase based on the ratio *** between the price of two different token pairs on *** Uniswap *** *** - minimalist design *** - low gas design *** - free for anyone to call. *** ****/ contract RebaseDelta { using RB_SafeMath for uint256; using RB_UnsignedSafeMath for int256; uint256 private constant PRICE_PRECISION = 10**9; function getPrice(IUniswapV2Pair pair_, bool flip_) public view returns (uint256) { require(address(pair_) != address(0)); (uint256 reserves0, uint256 reserves1, ) = pair_.getReserves(); if (flip_) { (reserves0, reserves1) = (reserves1, reserves0); } // reserves0 = base (probably ETH/WETH) // reserves1 = token of interest (maybe ampleforthgold or paxusgold etc) // multiply to equate decimals, multiply up to PRICE_PRECISION uint256 price = (reserves1.mul(PRICE_PRECISION)).div(reserves0); return price; } // calculates the supply delta for moving the price of token X to the price // of token Y (with the understanding that they are both priced in a common // tokens value, i.e. WETH). function calculate(IUniswapV2Pair X_, bool flipX_, uint256 decimalsX_, uint256 SupplyX_, IUniswapV2Pair Y_, bool flipY_, uint256 decimalsY_) public view returns (int256) { uint256 px = getPrice(X_, flipX_); require(px != uint256(0)); uint256 py = getPrice(Y_, flipY_); require(py != uint256(0)); uint256 targetSupply = (SupplyX_.mul(py)).div(px); // adust for decimals if (decimalsX_ == decimalsY_) { // do nothing } else if (decimalsX_ > decimalsY_) { uint256 ddg = (10**decimalsX_).div(10**decimalsY_); require (ddg != uint256(0)); targetSupply = targetSupply.mul(ddg); } else { uint256 ddl = (10**decimalsY_).div(10**decimalsX_); require (ddl != uint256(0)); targetSupply = targetSupply.div(ddl); } int256 delta = int256(SupplyX_).sub(int256(targetSupply)); return delta; } } //==Developed and deployed by the AmpleForthGold Team: https://ampleforth.gold // With thanks to: // https://github.com/Auric-Goldfinger // https://github.com/z0sim0s // https://github.com/Aurum-hub /** * @title Orchestrator * @notice The orchestrator is the main entry point for rebase operations. It coordinates the rebase * actions with external consumers (price oracles) and provides timing / access control for when a * rebase occurs. * * Orchestrator is based on Ampleforth.org implmentation with modifications by the AmpleForthgold team. * It is a merge and modification of the Orchestrator.sol and UFragmentsPolicy.sol from the original * Ampleforth project. Thanks to the Ampleforth.org team! * * Code ideas also come from the RMPL.IO (RAmple Project), YAM team and BASED team. * Thanks to the all whoose ideas we stole! * * We have simplifed the design to lower the gas fees. In some places we have removed things that were * "nice to have" because of the cost of GAS. Specifically we have lowered the number of events and * hard coded things that we know are going to be constant (such as not looking up a uniswap pair, * we just pass the pair pointer into the contract). This was done to save GAS and lower the execution * cost of the contract. * * The Price used for rebase calculations shall be sourced from Uniswap (on chain liquidity pools). * * Relying on price Oracles (either on chain or off chain) will never be perfect. Oracles go bad, * others come good. At present we will use liquidity pools on uniswap to provide the oracles * for pricing. However those oracles may go bad and need to be replaced. We think that oracle * failure in the short term is unlikly, but not impossible. In the long term it may be likely * to see oracle failure. Due to this the contract 'owners' (the AmpleForthGold team) shall * have an 'off switch' in the code to disable and override rebase operations. At some point * it may be needed...but we hope it is not needed. * */ contract Orchestrator is Ownable { using SafeMath for uint16; using SafeMath for uint256; using SafeMathInt for int256; // The ERC20 Token for ampleforthgold UFragments public afgToken = UFragments(0x8E54954B3Bbc07DbE3349AEBb6EAFf8D91Db5734); // oracle configuration - see RebaseDelta.sol for details. RebaseDelta public oracle = RebaseDelta(0xF09402111AF6409B410A8Dd07B82F1cd1674C55F); IUniswapV2Pair public tokenPairX = IUniswapV2Pair(0x2d0C51C1282c31d71F035E15770f3214e20F6150); IUniswapV2Pair public tokenPairY = IUniswapV2Pair(0x9C4Fe5FFD9A9fC5678cFBd93Aa2D4FD684b67C4C); bool public flipX = false; bool public flipY = false; uint8 public decimalsX = 9; uint8 public decimalsY = 9; // The timestamp of the last rebase event generated from this contract. // Technically another contract cauld also cause a rebase event, // so this cannot be relied on globally. uint64 should not clock // over in forever. uint64 public lastRebase = uint64(0); // The number of rebase cycles since inception. Why the original // designers did not keep this inside uFragments is a question // that really deservers an answer? We can use a uint16 cause we // will be about 179 years old before it clocks over. uint16 public epoch = 3; // Transactions are used to generate call back to DEXs that need to be // informed about rebase events. Specifically with uniswap the function // on the IUniswapV2Pair.sync() needs to be called so that the // liquidity pool can reset it reserves to the correct value. // ...Stable transaction ordering is not guaranteed. struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint index, bytes data); Transaction[] public transactions; /** * Just initializes the base class. */ constructor() public { Ownable.initialize(msg.sender); } /** * @notice Owner entry point to initiate a rebase operation. * @param supplyDelta the delta as passed to afgToken.rebase. * (the delta needs to be calulated off chain or by the * calling contract). * @param disable_ passing true will disable the ability of * users (other then the owner) to cause a rebase. * * The owner can always generate a rebase operation. At some point in the future * the owners keys shall be burnt. However at this time (and until we are certain * everthing is working as it should) the owners shall keep their keys. * The ability for the owners to generate a rebase of any value at any time is a * carry over from the original ampleforth project. This function is just a little * more direct. */ function ownerForcedRebase(int256 supplyDelta, bool disable_) external onlyOwner { /* If lastrebase is set to 0 then *users* cannot cause a rebase. * This should allow the owner to disable the auto-rebase operations if * things go wrong (see things go wrong above). */ if (disable_) { lastRebase = uint64(0); } else { lastRebase = uint64(block.timestamp); } afgToken.rebase(epoch.add(1), supplyDelta); popTransactionList(); } /** * @notice Main entry point to initiate a rebase operation. * On success returns the new supply value. */ function rebase() external returns (uint256) { // The owner shall call this member for the following reasons: // (1) Something went wrong and we need a rebase now! // (2) At some random time at least 24 hours, but no more then 48 // hours after the last rebase. if (Ownable.isOwner()) { return internal_rebase(); } // we require at least 1 owner rebase event prior to being enabled! require (lastRebase != uint64(0)); // at least 24 hours shall have passed since the last rebase event. require (lastRebase + 1 days < uint64(block.timestamp)); // if more then 48 hours have passed then allow a rebase from anyone // willing to pay the GAS. if (lastRebase + 2 days < uint64(block.timestamp)) { return internal_rebase(); } // There is (currently) no way of generating a random number in a // contract that cannot be seen/used by the miner. Thus a big miner // could use information on a rebase for their advantage. We do not // want to give any advantage to a big miner over a little trader, // thus the traders ability to generate and see a rebase (ahead of time) // should be about the same as a that of a large miners. // // If (in the future) the ability to provide true randomeness // changes then we would like to re-write this bit of code to provide // true random rebases where no one gets an advantage. // // A day after the last rebase, anyone can call this rebase function // to generate a rebase. However to give it a little bit of complexity // and mildly lower the ability of traders/miners to take advantage // of the rebase we will set the *fair* odds of a rebase() call // succeeding at 20%. Of course it can still be gamed, but this // makes gaming it just that little bit harder. // // MINERS: To game it the miner would need to adjust his coinbase to // correctly solve the xor with the preceeding block hashs, // That is do-able, but the miner would need to go out of there // way to do it...but no perfect solutions so this is it at the // moment. // // TRADERS: To game it they could just call this function many times // until it triggers. They have a 20% chance of triggering each // time they call it. They could get lucky, or they could burn a lot of // GAS. Whatever they do it will be obvious from the many calls to this // function. uint256 odds = uint256(blockhash(block.number - 1)) ^ uint256(block.coinbase); if ((odds % uint256(5)) == uint256(1)) { return internal_rebase(); } // no change, no rebase! return uint256(0); } /** * @notice Internal entry point to initiate a rebase operation. * If we get here then a rebase call to the erc20 token * will occur. * * returns the new supply value. */ function internal_rebase() private returns(uint256) { lastRebase = uint64(block.timestamp); uint256 z = afgToken.rebase(epoch.add(1), calculateRebaseDelta(true)); popTransactionList(); return z; } /** * @notice Configures the oracle & information passed to the oracle * to calculate the rebase. See RebaseDelta for definition * of params. * * Initially tokenPairX is the uniswap pair for AAU/WETH * and tokenPairY is the uniswap pair for PAXG/WETH. * These addresses can be verified on etherscan.io. */ function configureOracle(IUniswapV2Pair tokenPairX_, bool flipX_, uint8 decimalsX_, IUniswapV2Pair tokenPairY_, bool flipY_, uint8 decimalsY_, RebaseDelta oracle_) external onlyOwner { tokenPairX = tokenPairX_; flipX = flipX_; decimalsX = decimalsX_; tokenPairY = tokenPairY_; flipY = flipY_; decimalsY = decimalsY_; oracle = oracle_; } /** * @notice tries to calculate a rebase based on the configured oracle info. * * @param limited_ passing true will limit the rebase based on the 5% rule. */ function calculateRebaseDelta(bool limited_) public view returns (int256) { require (afgToken != UFragments(0)); require (oracle != RebaseDelta(0)); require (tokenPairX != IUniswapV2Pair(0)); require (tokenPairY != IUniswapV2Pair(0)); require (decimalsX != uint8(0)); require (decimalsY != uint8(0)); uint256 supply = afgToken.totalSupply(); int256 delta = - oracle.calculate( tokenPairX, flipX, decimalsX, supply, tokenPairY, flipY, decimalsY); if (!limited_) { // Unlimited (brutal) rebase. return delta; } if (delta == int256(0)) { // no rebase needed! return int256(0); } /** 5% rules: * (1) If the price is in the +-5% range do not rebase at all. This * allows the market to fix the price to within a 10% range. * (2) If the price is within +-10% range then only rebase by 1%. * (3) If the price is more then +-10% then the change shall be half the * delta. i.e. if the price diff is -28% then the change will be -14%. */ int256 supply5p = int256(supply.div(uint256(20))); // 5% == 5/100 == 1/20 if (delta < int256(0)) { if (-delta < supply5p) { return int256(0); // no rebase: 5% rule (1) } if (-delta < supply5p.mul(int256(2))) { return (-supply5p).div(int256(5)); // -1% rebase } } else { if (delta < supply5p) { return int256(0); // no rebase: 5% rule (1) } if (delta < supply5p.mul(int256(2))) { return supply5p.div(int256(5)); // +1% rebase } } return (delta.div(2)); // half delta rebase } // for testing purposes only! // winds back time a day at a time. function windbacktime() public onlyOwner { require (lastRebase > 1 days); lastRebase-= 1 days; } //===TRANSACTION FUNCTIONALITY (mostly identical to original Ampleforth implementation) /* generates callbacks after a rebase */ function popTransactionList() private { // we are getting an AAU price feed from this uniswap pair, thus when the rebase occurs // we need to ask it to rebase the AAU tokens in the pair. We always know this needs // to be done, so no use making a transcation for it. if (tokenPairX != IUniswapV2Pair(0)) { tokenPairX.sync(); } // iterate thru other interested parties and generate a call to update their // contracts. for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @return Number of transactions, both enabled and disabled, in transactions list. */ function transactionsSize() external view returns (uint256) { return transactions.length; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
Configures the oracle & information passed to the oracle to calculate the rebase. See RebaseDelta for definition of params. Initially tokenPairX is the uniswap pair for AAU/WETH and tokenPairY is the uniswap pair for PAXG/WETH. These addresses can be verified on etherscan.io./
function configureOracle(IUniswapV2Pair tokenPairX_, bool flipX_, uint8 decimalsX_, IUniswapV2Pair tokenPairY_, bool flipY_, uint8 decimalsY_, RebaseDelta oracle_) external onlyOwner { tokenPairX = tokenPairX_; flipX = flipX_; decimalsX = decimalsX_; tokenPairY = tokenPairY_; flipY = flipY_; decimalsY = decimalsY_; oracle = oracle_; }
131,800
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LizardLab is ERC721, Ownable { using Address for address; //some call it 'provenance' string public PROOF_OF_ANCESTRY; //where the wild things are (or will be) string public baseURI; //fives are good numbers... lets go with 5s uint256 public constant MAX_LIZARDS = 5000; uint256 public constant PRICE = 0.05 ether; uint256 public constant FOR_THE_WARCHEST = 100; uint256 public totalSupply; //do not get any ideas too soon bool public presaleActive = false; uint256 public presaleWave; bool public saleActive = false; //has [REDACTED] populated the war chest? bool public redactedClaimed = false; //who gets what address redLizard = 0xfb55e7ECbBA9715A9A9DD31DB3c777D8B98cB4Dc; address blueLizard = 0x87E9Ab2D6f4f744f36aad379f0157da30d3E2670; address greenLizard = 0x86bE508e686AB58ab9442c6A9800B1a941a6D60D; address warChest = 0x30471c24BDb0b9dDb75d9cA5D4E13049fc69FEfD; //some lizard keepers are...more privileged than others mapping (address => bool) public claimWhitelist; mapping (address => uint256) public presaleWhitelist; //there is a lot to unpack here constructor() ERC721("The Lizard Lab", "LIZRD") { } //don't let them all escape!! [REDACTED] needs them function recapture() public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length > 0, "No distributing Lizards until provenance is established."); require(!redactedClaimed, "Only once, even for you [REDACTED]"); require(totalSupply + FOR_THE_WARCHEST <= MAX_LIZARDS, "You have missed your chance, [REDACTED]."); for (uint256 i = 0; i < FOR_THE_WARCHEST; i++) { _safeMint(warChest, totalSupply + i); } totalSupply += FOR_THE_WARCHEST; redactedClaimed = true; } //a freebie for you, thank you for your support function claim() public { require(presaleActive || saleActive, "A sale period must be active to claim"); require(claimWhitelist[msg.sender], "No claim available for this address"); require(totalSupply + 1 <= MAX_LIZARDS, "Claim would exceed max supply of tokens"); _safeMint( msg.sender, totalSupply); totalSupply += 1; claimWhitelist[msg.sender] = false; } //thanks for hanging out.. function mintPresale(uint256 numberOfMints) public payable { uint256 reserved = presaleWhitelist[msg.sender]; require(presaleActive, "Presale must be active to mint"); require(reserved > 0, "No tokens reserved for this address"); require(numberOfMints <= reserved, "Can't mint more than reserved"); require(totalSupply + numberOfMints <= MAX_LIZARDS, "Purchase would exceed max supply of tokens"); require(PRICE * numberOfMints == msg.value, "Ether value sent is not correct"); presaleWhitelist[msg.sender] = reserved - numberOfMints; for(uint256 i; i < numberOfMints; i++){ _safeMint( msg.sender, totalSupply + i ); } totalSupply += numberOfMints; } //..and now for the rest of you function mint(uint256 numberOfMints) public payable { require(saleActive, "Sale must be active to mint"); require(numberOfMints > 0 && numberOfMints < 6, "Invalid purchase amount"); require(totalSupply + numberOfMints <= MAX_LIZARDS, "Purchase would exceed max supply of tokens"); require(PRICE * numberOfMints == msg.value, "Ether value sent is not correct"); for(uint256 i; i < numberOfMints; i++) { _safeMint(msg.sender, totalSupply + i); } totalSupply += numberOfMints; } //these lizards are free function editClaimList(address[] calldata claimAddresses) public onlyOwner { for(uint256 i; i < claimAddresses.length; i++){ claimWhitelist[claimAddresses[i]] = true; } } //somebody has to keep track of all of this function editPresaleList(address[] calldata presaleAddresses, uint256[] calldata amount) public onlyOwner { for(uint256 i; i < presaleAddresses.length; i++){ presaleWhitelist[presaleAddresses[i]] = amount[i]; } presaleWave = presaleWave + 1; } //[REDACTED] made me put this here..as to not..tinker with anything function setAncestry(string memory provenance) public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length == 0, "Now now, [REDACTED], do not go and try to play god...twice."); PROOF_OF_ANCESTRY = provenance; } //and a flip of the (small) switch function togglePresale() public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length > 0, "No distributing Lizards until provenance is established."); presaleActive = !presaleActive; } //the flip of a slightly larger switch function toggleSale() public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length > 0, "No distributing Lizards until provenance is established."); presaleActive = false; saleActive = !saleActive; } //for the grand reveal and where things are now.. where things will forever be.. lizards willing function setBaseURI(string memory uri) public onlyOwner { baseURI = uri; } //come have a looksy function _baseURI() internal view override returns (string memory) { return baseURI; } //coins for the lizards function withdraw() public { uint256 balance = address(this).balance; payable(redLizard).transfer((balance * 400) / 1000); payable(greenLizard).transfer((balance * 400) / 1000); payable(blueLizard).transfer((balance * 200) / 1000); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
and a flip of the (small) switch
function togglePresale() public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length > 0, "No distributing Lizards until provenance is established."); presaleActive = !presaleActive; }
13,731,544
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "./RewardsDistributorStorage.sol"; contract RewardsDistributorDelegator is RewardsDistributorDelegatorStorage { /// @notice Emitted when implementation is changed event NewImplementation(address oldImplementation, address newImplementation); constructor( address admin_, address rewardToken_, address implementation_) public { // Admin set to msg.sender for initialization admin = msg.sender; delegateTo(implementation_, abi.encodeWithSignature("initialize(address)", rewardToken_)); _setImplementation(implementation_); admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation */ function _setImplementation(address implementation_) public { require(msg.sender == admin, "RewardsDistributorDelegator::_setImplementation: admin only"); require(implementation_ != address(0), "RewardsDistributorDelegator::_setImplementation: invalid implementation address"); address oldImplementation = implementation; implementation = implementation_; emit NewImplementation(oldImplementation, implementation); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall */ function delegateTo(address callee, bytes memory data) internal { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () external payable { // delegate all other functions to current implementation (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "./CToken.sol"; contract RewardsDistributorDelegatorStorage { /// @notice Administrator for this contract address public admin; /// @notice Pending administrator for this contract address public pendingAdmin; /// @notice Active brains of RewardsDistributor address public implementation; } /** * @title Storage for RewardsDistributorDelegate * @notice For future upgrades, do not change RewardsDistributorDelegateStorageV1. Create a new * contract which implements RewardsDistributorDelegateStorageV1 and following the naming convention * RewardsDistributorDelegateStorageVX. */ contract RewardsDistributorDelegateStorageV1 is RewardsDistributorDelegatorStorage { /// @dev The token to reward (i.e., COMP) address public rewardToken; struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSupplySpeeds; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compBorrowSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; /// @notice The portion of COMP that each contributor receives per block mapping(address => uint) public compContributorSpeeds; /// @notice Last block at which a contributor's COMP rewards have been allocated mapping(address => uint) public lastContributorBlock; } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Returns a boolean indicating if the sender has admin rights */ function hasAdminRights() internal view returns (bool) { ComptrollerV3Storage comptrollerStorage = ComptrollerV3Storage(address(comptroller)); return (msg.sender == comptrollerStorage.admin() && comptrollerStorage.adminHasRights()) || (msg.sender == address(fuseAdmin) && comptrollerStorage.fuseAdminHasRights()); } /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, uint256 reserveFactorMantissa_, uint256 adminFeeMantissa_) public { require(msg.sender == address(fuseAdmin), "!admin"); require(accrualBlockNumber == 0 && borrowIndex == 0, "init"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "zero rate"); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "comptroller"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "irm"); name = name_; symbol = symbol_; decimals = decimals_; // Set reserve factor err = _setReserveFactorFresh(reserveFactorMantissa_); require(err == uint(Error.NO_ERROR), "reserve factor"); // Set admin fee err = _setAdminFeeFresh(adminFeeMantissa_); require(err == uint(Error.NO_ERROR), "fee"); // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @dev Returns latest pending Fuse fee (to be set with `_setFuseFeeFresh`) */ function getPendingFuseFeeFromAdmin() internal view returns (uint) { return fuseAdmin.interestFeeRate(); } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); /* We call the defense hook */ // unused function // comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant(false) returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant(false) returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "bal"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, add_(totalReserves, add_(totalAdminFees, totalFuseFees))); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, add_(totalReserves, add_(totalAdminFees, totalFuseFees)), reserveFactorMantissa + fuseFeeMantissa + adminFeeMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant(false) returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "acc"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant(false) returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "acc"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBal"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant(false) returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "acc"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exRate"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - (totalReserves + totalFuseFees + totalAdminFees)) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, add_(totalReserves, add_(totalAdminFees, totalFuseFees))); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); /* Short-circuit accumulating 0 interest */ if (accrualBlockNumber == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, totalBorrows, add_(totalReserves, add_(totalAdminFees, totalFuseFees))); require(borrowRateMantissa <= borrowRateMaxMantissa, "bor"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumber); require(mathErr == MathError.NO_ERROR, "sub"); return finishInterestAccrual(currentBlockNumber, cashPrior, borrowRateMantissa, blockDelta); } /** * @dev Split off from `accrueInterest` to avoid "stack too deep" error". */ function finishInterestAccrual(uint currentBlockNumber, uint cashPrior, uint borrowRateMantissa, uint blockDelta) private returns (uint) { /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * totalFuseFeesNew = interestAccumulated * fuseFee + totalFuseFees * totalAdminFeesNew = interestAccumulated * adminFee + totalAdminFees * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, totalBorrows); uint totalBorrowsNew = add_(interestAccumulated, totalBorrows); uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, totalReserves); uint totalFuseFeesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: fuseFeeMantissa}), interestAccumulated, totalFuseFees); uint totalAdminFeesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: adminFeeMantissa}), interestAccumulated, totalAdminFees); uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndex, borrowIndex); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; totalFuseFees = totalFuseFeesNew; totalAdminFees = totalAdminFeesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); // Attempt to add interest checkpoint address(interestRateModel).call(abi.encodeWithSignature("checkpointInterest(uint256)", borrowRateMantissa)); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant(false) returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } // Check max supply // unused function /* allowed = comptroller.mintWithinLimits(address(this), vars.exchangeRateMantissa, accountTokens[minter], mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } */ ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ vars.totalSupplyNew = add_(totalSupply, vars.mintTokens); vars.accountTokensNew = add_(accountTokens[minter], vars.mintTokens); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant(false) returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant(false) returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeem"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant(false) returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ uint cashPrior = getCashPrior(); if (cashPrior < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } // Check min borrow for this user for this asset allowed = comptroller.borrowWithinLimits(address(this), vars.accountBorrowsNew); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant(false) returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant(false) returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant(false) returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQ"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQ"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "seize"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant(true) returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } struct SeizeInternalLocalVars { MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; uint liquidatorSeizeTokens; uint protocolSeizeTokens; uint protocolSeizeAmount; uint exchangeRateMantissa; uint totalReservesNew; uint totalSupplyNew; } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } SeizeInternalLocalVars memory vars; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (vars.mathErr, vars.borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(vars.mathErr)); } vars.protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa})); vars.liquidatorSeizeTokens = sub_(seizeTokens, vars.protocolSeizeTokens); (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); require(vars.mathErr == MathError.NO_ERROR, "exRate"); vars.protocolSeizeAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), vars.protocolSeizeTokens); vars.totalReservesNew = add_(totalReserves, vars.protocolSeizeAmount); vars.totalSupplyNew = sub_(totalSupply, vars.protocolSeizeTokens); (vars.mathErr, vars.liquidatorTokensNew) = addUInt(accountTokens[liquidator], vars.liquidatorSeizeTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ totalReserves = vars.totalReservesNew; totalSupply = vars.totalSupplyNew; accountTokens[borrower] = vars.borrowerTokensNew; accountTokens[liquidator] = vars.liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, vars.liquidatorSeizeTokens); emit Transfer(borrower, address(this), vars.protocolSeizeTokens); emit ReservesAdded(address(this), vars.protocolSeizeAmount, vars.totalReservesNew); /* We call the defense hook */ // unused function // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Sets a new comptroller for the market * @dev Internal function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) internal returns (uint) { ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new admin fee for the protocol using _setAdminFeeFresh * @dev Admin function to accrue interest and set a new admin fee * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setAdminFee(uint newAdminFeeMantissa) external nonReentrant(false) returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted admin fee change failed. return fail(Error(error), FailureInfo.SET_ADMIN_FEE_ACCRUE_INTEREST_FAILED); } // _setAdminFeeFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setAdminFeeFresh(newAdminFeeMantissa); } /** * @notice Sets a new admin fee for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new admin fee * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setAdminFeeFresh(uint newAdminFeeMantissa) internal returns (uint) { // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_ADMIN_FEE_FRESH_CHECK); } // Sanitize newAdminFeeMantissa if (newAdminFeeMantissa == uint(-1)) newAdminFeeMantissa = adminFeeMantissa; // Get latest Fuse fee uint newFuseFeeMantissa = getPendingFuseFeeFromAdmin(); // Check reserveFactorMantissa + newAdminFeeMantissa + newFuseFeeMantissa ≤ reserveFactorPlusFeesMaxMantissa if (add_(add_(reserveFactorMantissa, newAdminFeeMantissa), newFuseFeeMantissa) > reserveFactorPlusFeesMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_ADMIN_FEE_BOUNDS_CHECK); } // If setting admin fee if (adminFeeMantissa != newAdminFeeMantissa) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ADMIN_FEE_ADMIN_CHECK); } // Set admin fee uint oldAdminFeeMantissa = adminFeeMantissa; adminFeeMantissa = newAdminFeeMantissa; // Emit event emit NewAdminFee(oldAdminFeeMantissa, newAdminFeeMantissa); } // If setting Fuse fee if (fuseFeeMantissa != newFuseFeeMantissa) { // Set Fuse fee uint oldFuseFeeMantissa = fuseFeeMantissa; fuseFeeMantissa = newFuseFeeMantissa; // Emit event emit NewFuseFee(oldFuseFeeMantissa, newFuseFeeMantissa); } return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant(false) returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (add_(add_(newReserveFactorMantissa, adminFeeMantissa), fuseFeeMantissa) > reserveFactorPlusFeesMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant(false) returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We checked reduceAmount <= totalReserves above, so this should never revert. totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(msg.sender, reduceAmount); emit ReservesReduced(msg.sender, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces Fuse fees by transferring to Fuse * @param withdrawAmount Amount of fees to withdraw * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawFuseFees(uint withdrawAmount) external nonReentrant(false) returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted Fuse fee withdrawal failed. return fail(Error(error), FailureInfo.WITHDRAW_FUSE_FEES_ACCRUE_INTEREST_FAILED); } // _withdrawFuseFeesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _withdrawFuseFeesFresh(withdrawAmount); } /** * @notice Reduces Fuse fees by transferring to Fuse * @dev Requires fresh interest accrual * @param withdrawAmount Amount of fees to withdraw * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawFuseFeesFresh(uint withdrawAmount) internal returns (uint) { // totalFuseFees - reduceAmount uint totalFuseFeesNew; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.WITHDRAW_FUSE_FEES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < withdrawAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_FUSE_FEES_CASH_NOT_AVAILABLE); } // Check withdrawAmount ≤ fuseFees[n] (totalFuseFees) if (withdrawAmount > totalFuseFees) { return fail(Error.BAD_INPUT, FailureInfo.WITHDRAW_FUSE_FEES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We checked withdrawAmount <= totalFuseFees above, so this should never revert. totalFuseFeesNew = sub_(totalFuseFees, withdrawAmount); // Store fuseFees[n+1] = fuseFees[n] - withdrawAmount totalFuseFees = totalFuseFeesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(address(fuseAdmin), withdrawAmount); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces admin fees by transferring to admin * @param withdrawAmount Amount of fees to withdraw * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawAdminFees(uint withdrawAmount) external nonReentrant(false) returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted admin fee withdrawal failed. return fail(Error(error), FailureInfo.WITHDRAW_ADMIN_FEES_ACCRUE_INTEREST_FAILED); } // _withdrawAdminFeesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _withdrawAdminFeesFresh(withdrawAmount); } /** * @notice Reduces admin fees by transferring to admin * @dev Requires fresh interest accrual * @param withdrawAmount Amount of fees to withdraw * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawAdminFeesFresh(uint withdrawAmount) internal returns (uint) { // totalAdminFees - reduceAmount uint totalAdminFeesNew; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.WITHDRAW_ADMIN_FEES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < withdrawAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_ADMIN_FEES_CASH_NOT_AVAILABLE); } // Check withdrawAmount ≤ adminFees[n] (totalAdminFees) if (withdrawAmount > totalAdminFees) { return fail(Error.BAD_INPUT, FailureInfo.WITHDRAW_ADMIN_FEES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We checked withdrawAmount <= totalAdminFees above, so this should never revert. totalAdminFeesNew = sub_(totalAdminFees, withdrawAmount); // Store adminFees[n+1] = adminFees[n] - withdrawAmount totalAdminFees = totalAdminFeesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(address(uint160(UnitrollerAdminStorage(address(comptroller)).admin())), withdrawAmount); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); // Attempt to reset interest checkpoints on old IRM if (address(oldInterestRateModel) != address(0)) address(oldInterestRateModel).call(abi.encodeWithSignature("resetInterestCheckpoints()")); // Attempt to add first interest checkpoint on new IRM address(newInterestRateModel).call(abi.encodeWithSignature("checkpointInterest()")); return uint(Error.NO_ERROR); } /** * @notice updates the cToken ERC20 name and symbol * @dev Admin function to update the cToken ERC20 name and symbol * @param _name the new ERC20 token name to use * @param _symbol the new ERC20 token symbol to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setNameAndSymbol(string calldata _name, string calldata _symbol) external { // Check caller is admin require(hasAdminRights(), "!admin"); // Set ERC20 name and symbol name = _name; symbol = _symbol; } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant(bool localOnly) { _beforeNonReentrant(localOnly); _; _afterNonReentrant(localOnly); } /** * @dev Split off from `nonReentrant` to keep contract below the 24 KB size limit. * Saves space because function modifier code is "inlined" into every function with the modifier). * In this specific case, the optimization saves around 1500 bytes of that valuable 24 KB limit. */ function _beforeNonReentrant(bool localOnly) private { require(_notEntered, "re-entered"); if (!localOnly) comptroller._beforeNonReentrant(); _notEntered = false; } /** * @dev Split off from `nonReentrant` to keep contract below the 24 KB size limit. * Saves space because function modifier code is "inlined" into every function with the modifier). * In this specific case, the optimization saves around 150 bytes of that valuable 24 KB limit. */ function _afterNonReentrant(bool localOnly) private { _notEntered = true; // get a gas-refund post-Istanbul if (!localOnly) comptroller._afterNonReentrant(); } /** * @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`]. * @param data The call data (encoded using abi.encode or one of its variants). * @param errorMessage The revert string to return on failure. */ function _functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.call(data); if (!success) { // 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); } } return returndata; } } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintWithinLimits(address cToken, uint exchangeRateMantissa, uint accountTokens, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowWithinLimits(address cToken, uint accountBorrowsNew) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); /*** Pool-Wide/Cross-Asset Reentrancy Prevention ***/ function _beforeNonReentrant() external; function _afterNonReentrant() external; } pragma solidity ^0.5.16; import "./IFuseFeeDistributor.sol"; import "./ComptrollerStorage.sol"; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenAdminStorage { /** * @notice Administrator for Fuse */ IFuseFeeDistributor internal constant fuseAdmin = IFuseFeeDistributor(0xa731585ab05fC9f83555cf9Bff8F58ee94e18F85); /** * @dev LEGACY USE ONLY: Administrator for this contract */ address payable internal __admin; /** * @dev LEGACY USE ONLY: Whether or not the Fuse admin has admin rights */ bool internal __fuseAdminHasRights; /** * @dev LEGACY USE ONLY: Whether or not the admin has admin rights */ bool internal __adminHasRights; } contract CTokenStorage is CTokenAdminStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves + fees */ uint internal constant reserveFactorPlusFeesMaxMantissa = 1e18; /** * @notice LEGACY USE ONLY: Pending administrator for this contract */ address payable private __pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for admin fees */ uint public adminFeeMantissa; /** * @notice Fraction of interest currently set aside for Fuse fees */ uint public fuseFeeMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total amount of admin fees of the underlying held in this market */ uint public totalAdminFees; /** * @notice Total amount of Fuse fees of the underlying held in this market */ uint public totalFuseFees; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; /** * @notice Share of seized collateral that is added to reserves */ uint public constant protocolSeizeShareMantissa = 2.8e16; //2.8% } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /** * @notice Indicator that this is or is not a CEther contract (for inspection) */ bool public constant isCEther = false; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice Event emitted when the admin fee is changed */ event NewAdminFee(uint oldAdminFeeMantissa, uint newAdminFeeMantissa); /** * @notice Event emitted when the Fuse fee is changed */ event NewFuseFee(uint oldFuseFeeMantissa, uint newFuseFeeMantissa); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); } contract CEtherInterface is CErc20Storage { /** * @notice Indicator that this is a CEther contract (for inspection) */ bool public constant isCEther = true; } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegateInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementationSafe(address implementation_, bool allowResign, bytes calldata becomeImplementationData) external; /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes calldata data) external; /** * @notice Function called before all delegator functions * @dev Checks comptroller.autoImplementation and upgrades the implementation if necessary */ function _prepare() external payable; } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY, SUPPLIER_NOT_WHITELISTED, BORROW_BELOW_MIN, SUPPLY_ABOVE_MAX, NONZERO_TOTAL_SUPPLY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, ADD_REWARDS_DISTRIBUTOR_OWNER_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, TOGGLE_ADMIN_RIGHTS_OWNER_CHECK, TOGGLE_AUTO_IMPLEMENTATIONS_ENABLED_OWNER_CHECK, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_CONTRACT_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SET_WHITELIST_ENFORCEMENT_OWNER_CHECK, SET_WHITELIST_STATUS_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK, UNSUPPORT_MARKET_OWNER_CHECK, UNSUPPORT_MARKET_DOES_NOT_EXIST, UNSUPPORT_MARKET_IN_USE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED, UTILIZATION_ABOVE_MAX } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_FUSE_FEES_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_ADMIN_FEES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, NEW_UTILIZATION_RATE_ABOVE_MAX, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, WITHDRAW_FUSE_FEES_ACCRUE_INTEREST_FAILED, WITHDRAW_FUSE_FEES_CASH_NOT_AVAILABLE, WITHDRAW_FUSE_FEES_FRESH_CHECK, WITHDRAW_FUSE_FEES_VALIDATION, WITHDRAW_ADMIN_FEES_ACCRUE_INTEREST_FAILED, WITHDRAW_ADMIN_FEES_CASH_NOT_AVAILABLE, WITHDRAW_ADMIN_FEES_FRESH_CHECK, WITHDRAW_ADMIN_FEES_VALIDATION, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, TOGGLE_ADMIN_RIGHTS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_ADMIN_FEE_ACCRUE_INTEREST_FAILED, SET_ADMIN_FEE_ADMIN_CHECK, SET_ADMIN_FEE_FRESH_CHECK, SET_ADMIN_FEE_BOUNDS_CHECK, SET_FUSE_FEE_ACCRUE_INTEREST_FAILED, SET_FUSE_FEE_FRESH_CHECK, SET_FUSE_FEE_BOUNDS_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return err == Error.COMPTROLLER_REJECTION ? 1000 + opaqueError : uint(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; interface IFuseFeeDistributor { function minBorrowEth() external view returns (uint256); function maxSupplyEth() external view returns (uint256); function maxUtilizationRate() external view returns (uint256); function interestFeeRate() external view returns (uint256); function comptrollerImplementationWhitelist(address oldImplementation, address newImplementation) external view returns (bool); function cErc20DelegateWhitelist(address oldImplementation, address newImplementation, bool allowResign) external view returns (bool); function cEtherDelegateWhitelist(address oldImplementation, address newImplementation, bool allowResign) external view returns (bool); function latestComptrollerImplementation(address oldImplementation) external view returns (address); function latestCErc20Delegate(address oldImplementation) external view returns (address cErc20Delegate, bool allowResign, bytes memory becomeImplementationData); function latestCEtherDelegate(address oldImplementation) external view returns (address cEtherDelegate, bool allowResign, bytes memory becomeImplementationData); function deployCEther(bytes calldata constructorData) external returns (address); function deployCErc20(bytes calldata constructorData) external returns (address); function () external payable; } pragma solidity ^0.5.16; import "./IFuseFeeDistributor.sol"; import "./CToken.sol"; import "./PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for Fuse */ IFuseFeeDistributor internal constant fuseAdmin = IFuseFeeDistributor(0xa731585ab05fC9f83555cf9Bff8F58ee94e18F85); /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Whether or not the Fuse admin has admin rights */ bool public fuseAdminHasRights = true; /** * @notice Whether or not the admin has admin rights */ bool public adminHasRights = true; /** * @notice Returns a boolean indicating if the sender has admin rights */ function hasAdminRights() internal view returns (bool) { return (msg.sender == admin && adminHasRights) || (msg.sender == address(fuseAdmin) && fuseAdminHasRights); } /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice UNUSED AFTER UPGRADE: Max number of assets a single account can participate in (borrow or use as collateral) */ uint internal maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /** * @notice Whether or not this market is listed */ bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /** * @notice Per-market mapping of "accounts in this asset" */ mapping(address => bool) accountMembership; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /// @notice A list of all markets CToken[] public allMarkets; /** * @dev Maps borrowers to booleans indicating if they have entered any markets */ mapping(address => bool) internal borrowers; /// @notice A list of all borrowers who have entered markets address[] public allBorrowers; /// @notice Indexes of borrower account addresses in the `allBorrowers` array mapping(address => uint256) internal borrowerIndexes; /** * @dev Maps suppliers to booleans indicating if they have ever supplied to any markets */ mapping(address => bool) public suppliers; /// @notice All cTokens addresses mapped by their underlying token addresses mapping(address => CToken) public cTokensByUnderlying; /// @notice Whether or not the supplier whitelist is enforced bool public enforceWhitelist; /// @notice Maps addresses to booleans indicating if they are allowed to supply assets (i.e., mint cTokens) mapping(address => bool) public whitelist; /// @notice An array of all whitelisted accounts address[] public whitelistArray; /// @notice Indexes of account addresses in the `whitelistArray` array mapping(address => uint256) internal whitelistIndexes; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { /** * @dev Whether or not the implementation should be auto-upgraded. */ bool public autoImplementation; /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint) public supplyCaps; /// @notice RewardsDistributor contracts to notify of flywheel changes. address[] public rewardsDistributors; /// @dev Guard variable for pool-wide/cross-asset re-entrancy checks bool internal _notEntered; /// @dev Whether or not _notEntered has been initialized bool internal _notEnteredInitialized; } pragma solidity ^0.5.16; import "./CToken.sol"; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint); } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { 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 Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } }
User redeems cTokens in exchange for the underlying asset Assumes interest has already been accrued up to the current block redeemer The address of the account which is redeeming the tokens redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ exchangeRate = invoke Exchange Rate Stored() / If redeemTokensIn > 0: / Verify market's block number equals current block number / Fail gracefully if protocol has insufficient cash /
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeem"); RedeemLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } if (redeemTokensIn > 0) { vars.redeemTokens = redeemTokensIn; if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } accountTokens[redeemer] = vars.accountTokensNew; emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); }
486,314
./full_match/5/0xD1669a2845f4669c6C69263156c50DD3dE971a3D/sources/project_/contracts/dao/DAOCommittee.sol
Set CandidateFactory contract address _candidateFactory New CandidateFactory contract address
function setCandidateFactory( address _candidateFactory ) external override onlyOwner nonZero(_candidateFactory) { candidateFactory = ICandidateFactory(_candidateFactory); }
1,861,378
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; // Part: IBasicRewards interface IBasicRewards { function stakeFor(address, uint256) external returns (bool); function balanceOf(address) external view returns (uint256); function earned(address) external view returns (uint256); function withdrawAll(bool) external returns (bool); function withdraw(uint256, bool) external returns (bool); function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool); function getReward() external returns (bool); function stake(uint256) external returns (bool); function extraRewards(uint256) external view returns (address); } // Part: IBooster interface IBooster { function depositAll(uint256 _pid, bool _stake) external returns (bool); function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); function withdraw(uint256 _pid, uint256 _amount) external returns (bool); function withdrawAll(uint256 _pid) external returns (bool); } // Part: ICVXLocker interface ICVXLocker { function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function balances(address _user) external view returns ( uint112 locked, uint112 boosted, uint32 nextUnlockIndex ); } // Part: ICurveFactoryPool interface ICurveFactoryPool { function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_balances() external view returns (uint256[2] memory); function add_liquidity( uint256[2] memory _amounts, uint256 _min_mint_amount, address _receiver ) external returns (uint256); function exchange( int128 i, int128 j, uint256 _dx, uint256 _min_dy, address _receiver ) external returns (uint256); } // Part: ICurveTriCrypto interface ICurveTriCrypto { function exchange( uint256 i, uint256 j, uint256 dx, uint256 min_dy, bool use_eth ) external payable; function get_dy( uint256 i, uint256 j, uint256 dx ) external view returns (uint256); } // Part: ICurveV2Pool interface ICurveV2Pool { function get_dy( uint256 i, uint256 j, uint256 dx ) external view returns (uint256); function exchange_underlying( uint256 i, uint256 j, uint256 dx, uint256 min_dy ) external payable returns (uint256); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external returns (uint256); function future_A_gamma_time() external view returns (uint256); function lp_price() external view returns (uint256); } // Part: IMerkleDistributorV2 interface IMerkleDistributorV2 { enum Option { Claim, ClaimAsETH, ClaimAsCRV, ClaimAsCVX, ClaimAndStake } function vault() external view returns (address); function merkleRoot() external view returns (bytes32); function week() external view returns (uint32); function frozen() external view returns (bool); function isClaimed(uint256 index) external view returns (bool); function setApprovals() external; function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; function claimAs( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, Option option ) external; function claimAs( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, Option option, uint256 minAmountOut ) external; function freeze() external; function unfreeze() external; function stake() external; function updateMerkleRoot(bytes32 newMerkleRoot, bool unfreeze) external; function updateDepositor(address newDepositor) external; function updateAdmin(address newAdmin) external; function updateVault(address newVault) external; event Claimed( uint256 index, uint256 amount, address indexed account, uint256 indexed week, Option option ); event DepositorUpdated( address indexed oldDepositor, address indexed newDepositor ); event AdminUpdated(address indexed oldAdmin, address indexed newAdmin); event VaultUpdated(address indexed oldVault, address indexed newVault); event MerkleRootUpdated(bytes32 indexed merkleRoot, uint32 indexed week); } // Part: IRewards interface IRewards { function balanceOf(address) external view returns (uint256); function stake(address, uint256) external; function stakeFor(address, uint256) external; function withdraw(address, uint256) external; function exit(address) external; function getReward(address) external; function queueNewRewards(uint256) external; function notifyRewardAmount(uint256) external; function addExtraReward(address) external; function stakingToken() external view returns (address); function rewardToken() external view returns (address); function earned(address account) external view returns (uint256); } // Part: ITriPool interface ITriPool { function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function get_virtual_price() external view returns (uint256); } // Part: IUniV2Router interface IUniV2Router { function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: IUnionVault interface IUnionVault { enum Option { Claim, ClaimAsETH, ClaimAsCRV, ClaimAsCVX, ClaimAndStake } function withdraw(address _to, uint256 _shares) external returns (uint256 withdrawn); function withdrawAll(address _to) external returns (uint256 withdrawn); function withdrawAs( address _to, uint256 _shares, Option option ) external; function withdrawAs( address _to, uint256 _shares, Option option, uint256 minAmountOut ) external; function withdrawAllAs(address _to, Option option) external; function withdrawAllAs( address _to, Option option, uint256 minAmountOut ) external; function depositAll(address _to) external returns (uint256 _shares); function deposit(address _to, uint256 _amount) external returns (uint256 _shares); function harvest() external; function balanceOfUnderlying(address user) external view returns (uint256 amount); function outstanding3CrvRewards() external view returns (uint256 total); function outstandingCvxRewards() external view returns (uint256 total); function outstandingCrvRewards() external view returns (uint256 total); function totalUnderlying() external view returns (uint256 total); function underlying() external view returns (address); function setPlatform(address _platform) external; function setPlatformFee(uint256 _fee) external; function setCallIncentive(uint256 _incentive) external; function setWithdrawalPenalty(uint256 _penalty) external; function setApprovals() external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Ownable /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: UnionBase // Common variables and functions contract UnionBase { address public constant CVXCRV_STAKING_CONTRACT = 0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e; address public constant CURVE_CRV_ETH_POOL = 0x8301AE4fc9c624d1D396cbDAa1ed877821D7C511; address public constant CURVE_CVX_ETH_POOL = 0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4; address public constant CURVE_CVXCRV_CRV_POOL = 0x9D0464996170c6B9e75eED71c68B99dDEDf279e8; address public constant CRV_TOKEN = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant CVXCRV_TOKEN = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7; address public constant CVX_TOKEN = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; uint256 public constant CRVETH_ETH_INDEX = 0; uint256 public constant CRVETH_CRV_INDEX = 1; int128 public constant CVXCRV_CRV_INDEX = 0; int128 public constant CVXCRV_CVXCRV_INDEX = 1; uint256 public constant CVXETH_ETH_INDEX = 0; uint256 public constant CVXETH_CVX_INDEX = 1; IBasicRewards cvxCrvStaking = IBasicRewards(CVXCRV_STAKING_CONTRACT); ICurveV2Pool cvxEthSwap = ICurveV2Pool(CURVE_CVX_ETH_POOL); ICurveV2Pool crvEthSwap = ICurveV2Pool(CURVE_CRV_ETH_POOL); ICurveFactoryPool crvCvxCrvSwap = ICurveFactoryPool(CURVE_CVXCRV_CRV_POOL); /// @notice Swap CRV for cvxCRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @return amount of CRV obtained after the swap function _swapCrvToCvxCrv(uint256 amount, address recipient) internal returns (uint256) { return _crvToCvxCrv(amount, recipient, 0); } /// @notice Swap CRV for cvxCRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapCrvToCvxCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return _crvToCvxCrv(amount, recipient, minAmountOut); } /// @notice Swap CRV for cvxCRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _crvToCvxCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return crvCvxCrvSwap.exchange( CVXCRV_CRV_INDEX, CVXCRV_CVXCRV_INDEX, amount, minAmountOut, recipient ); } /// @notice Swap cvxCRV for CRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @return amount of CRV obtained after the swap function _swapCvxCrvToCrv(uint256 amount, address recipient) internal returns (uint256) { return _cvxCrvToCrv(amount, recipient, 0); } /// @notice Swap cvxCRV for CRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapCvxCrvToCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return _cvxCrvToCrv(amount, recipient, minAmountOut); } /// @notice Swap cvxCRV for CRV on Curve /// @param amount - amount to swap /// @param recipient - where swapped tokens will be sent to /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _cvxCrvToCrv( uint256 amount, address recipient, uint256 minAmountOut ) internal returns (uint256) { return crvCvxCrvSwap.exchange( CVXCRV_CVXCRV_INDEX, CVXCRV_CRV_INDEX, amount, minAmountOut, recipient ); } /// @notice Swap CRV for native ETH on Curve /// @param amount - amount to swap /// @return amount of ETH obtained after the swap function _swapCrvToEth(uint256 amount) internal returns (uint256) { return _crvToEth(amount, 0); } /// @notice Swap CRV for native ETH on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of ETH obtained after the swap function _swapCrvToEth(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return _crvToEth(amount, minAmountOut); } /// @notice Swap CRV for native ETH on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of ETH obtained after the swap function _crvToEth(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return crvEthSwap.exchange_underlying{value: 0}( CRVETH_CRV_INDEX, CRVETH_ETH_INDEX, amount, minAmountOut ); } /// @notice Swap native ETH for CRV on Curve /// @param amount - amount to swap /// @return amount of CRV obtained after the swap function _swapEthToCrv(uint256 amount) internal returns (uint256) { return _ethToCrv(amount, 0); } /// @notice Swap native ETH for CRV on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapEthToCrv(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return _ethToCrv(amount, minAmountOut); } /// @notice Swap native ETH for CRV on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _ethToCrv(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return crvEthSwap.exchange_underlying{value: amount}( CRVETH_ETH_INDEX, CRVETH_CRV_INDEX, amount, minAmountOut ); } /// @notice Swap native ETH for CVX on Curve /// @param amount - amount to swap /// @return amount of CRV obtained after the swap function _swapEthToCvx(uint256 amount) internal returns (uint256) { return _ethToCvx(amount, 0); } /// @notice Swap native ETH for CVX on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _swapEthToCvx(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return _ethToCvx(amount, minAmountOut); } /// @notice Swap native ETH for CVX on Curve /// @param amount - amount to swap /// @param minAmountOut - minimum expected amount of output tokens /// @return amount of CRV obtained after the swap function _ethToCvx(uint256 amount, uint256 minAmountOut) internal returns (uint256) { return cvxEthSwap.exchange_underlying{value: amount}( CVXETH_ETH_INDEX, CVXETH_CVX_INDEX, amount, minAmountOut ); } modifier notToZeroAddress(address _to) { require(_to != address(0), "Invalid address!"); _; } } // File: ExtraZaps.sol contract ExtraZaps is Ownable, UnionBase { using SafeERC20 for IERC20; address public immutable vault; address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address private constant TRICRYPTO = 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46; address private constant TRIPOOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address private constant TRICRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address private constant BOOSTER = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; address private constant CONVEX_TRIPOOL_TOKEN = 0x30D9410ED1D5DA1F6C8391af5338C93ab8d4035C; address private constant CONVEX_TRIPOOL_REWARDS = 0x689440f2Ff927E1f24c72F1087E1FAF471eCe1c8; address private constant CONVEX_LOCKER = 0x72a19342e8F1838460eBFCCEf09F6585e32db86E; ICurveTriCrypto triCryptoSwap = ICurveTriCrypto(TRICRYPTO); ITriPool triPool = ITriPool(TRIPOOL); IBooster booster = IBooster(BOOSTER); IRewards triPoolRewards = IRewards(CONVEX_TRIPOOL_REWARDS); ICVXLocker locker = ICVXLocker(CONVEX_LOCKER); IMerkleDistributorV2 distributor; constructor(address _vault, address _distributor) { vault = _vault; distributor = IMerkleDistributorV2(_distributor); } function setApprovals() external { IERC20(TRICRV).safeApprove(BOOSTER, 0); IERC20(TRICRV).safeApprove(BOOSTER, type(uint256).max); IERC20(USDT).safeApprove(TRIPOOL, 0); IERC20(USDT).safeApprove(TRIPOOL, type(uint256).max); IERC20(CONVEX_TRIPOOL_TOKEN).safeApprove(CONVEX_TRIPOOL_REWARDS, 0); IERC20(CONVEX_TRIPOOL_TOKEN).safeApprove( CONVEX_TRIPOOL_REWARDS, type(uint256).max ); IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 0); IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, type(uint256).max); IERC20(CVXCRV_TOKEN).safeApprove(vault, 0); IERC20(CVXCRV_TOKEN).safeApprove(vault, type(uint256).max); IERC20(CVX).safeApprove(CONVEX_LOCKER, 0); IERC20(CVX).safeApprove(CONVEX_LOCKER, type(uint256).max); } /// @notice Retrieves user's uCRV and unstake to ETH /// @param amount - the amount of uCRV to unstake function _withdrawFromVaultAsEth(uint256 amount) internal { IERC20(vault).safeTransferFrom(msg.sender, address(this), amount); IUnionVault(vault).withdrawAllAs( address(this), IUnionVault.Option.ClaimAsETH ); } /// @notice swap ETH to USDT via Curve's tricrypto /// @param amount - the amount of ETH to swap /// @param minAmountOut - the minimum amount expected function _swapEthToUsdt( uint256 amount, uint256 minAmountOut, address to ) internal { triCryptoSwap.exchange{value: amount}( 2, // ETH 0, // USDT amount, minAmountOut, true ); } /// @notice Unstake from the Pounder to USDT /// @param amount - the amount of uCRV to unstake /// @param minAmountOut - the min expected amount of USDT to receive /// @param to - the adress that will receive the USDT /// @return amount of USDT obtained function claimFromVaultAsUsdt( uint256 amount, uint256 minAmountOut, address to ) public notToZeroAddress(to) returns (uint256) { _withdrawFromVaultAsEth(amount); _swapEthToUsdt(address(this).balance, minAmountOut, to); uint256 _usdtAmount = IERC20(USDT).balanceOf(address(this)); if (to != address(this)) { IERC20(USDT).safeTransfer(to, _usdtAmount); } return _usdtAmount; } /// @notice Claim from the distributor, unstake and returns USDT. /// @param index - claimer index /// @param account - claimer account /// @param amount - claim amount /// @param merkleProof - merkle proof for the claim /// @param minAmountOut - the min expected amount of USDT to receive /// @param to - the adress that will receive the USDT /// @return amount of USDT obtained function claimFromDistributorAsUsdt( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address to ) external notToZeroAddress(to) returns (uint256) { distributor.claim(index, account, amount, merkleProof); return claimFromVaultAsUsdt(amount, minAmountOut, to); } /// @notice Unstake from the Pounder to stables and stake on 3pool convex for yield /// @param amount - amount of uCRV to unstake /// @param minAmountOut - minimum amount of 3CRV (NOT USDT!) /// @param to - address on behalf of which to stake function claimFromVaultAndStakeIn3PoolConvex( uint256 amount, uint256 minAmountOut, address to ) public notToZeroAddress(to) { // claim as USDT uint256 _usdtAmount = claimFromVaultAsUsdt(amount, 0, address(this)); // add USDT to Tripool triPool.add_liquidity([0, 0, _usdtAmount], minAmountOut); // deposit on Convex booster.depositAll(9, false); // stake on behalf of user triPoolRewards.stakeFor( to, IERC20(CONVEX_TRIPOOL_TOKEN).balanceOf(address(this)) ); } /// @notice Claim from the distributor, unstake and deposits in 3pool. /// @param index - claimer index /// @param account - claimer account /// @param amount - claim amount /// @param merkleProof - merkle proof for the claim /// @param minAmountOut - minimum amount of 3CRV (NOT USDT!) /// @param to - address on behalf of which to stake function claimFromDistributorAndStakeIn3PoolConvex( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address to ) external notToZeroAddress(to) { distributor.claim(index, account, amount, merkleProof); claimFromVaultAndStakeIn3PoolConvex(amount, minAmountOut, to); } /// @notice Claim to any token via a univ2 router /// @notice Use at your own risk /// @param amount - amount of uCRV to unstake /// @param minAmountOut - min amount of output token expected /// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi /// @param outputToken - address of the token to swap to /// @param to - address of the final recipient of the swapped tokens function claimFromVaultViaUniV2EthPair( uint256 amount, uint256 minAmountOut, address router, address outputToken, address to ) public notToZeroAddress(to) { require(router != address(0)); _withdrawFromVaultAsEth(amount); address[] memory _path = new address[](2); _path[0] = WETH; _path[1] = outputToken; IUniV2Router(router).swapExactETHForTokens{ value: address(this).balance }(minAmountOut, _path, to, block.timestamp + 60); } /// @notice Claim to any token via a univ2 router /// @notice Use at your own risk /// @param amount - amount of uCRV to unstake /// @param minAmountOut - min amount of output token expected /// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi /// @param outputToken - address of the token to swap to /// @param to - address of the final recipient of the swapped tokens function claimFromDistributorViaUniV2EthPair( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address router, address outputToken, address to ) external notToZeroAddress(to) { distributor.claim(index, account, amount, merkleProof); claimFromVaultViaUniV2EthPair( amount, minAmountOut, router, outputToken, to ); } /// @notice Unstake from the Pounder as CVX and locks it /// @param amount - amount of uCRV to unstake /// @param minAmountOut - min amount of CVX expected /// @param to - address to lock on behalf of function claimFromVaultAsCvxAndLock( uint256 amount, uint256 minAmountOut, address to ) public notToZeroAddress(to) { IERC20(vault).safeTransferFrom(msg.sender, address(this), amount); IUnionVault(vault).withdrawAllAs( address(this), IUnionVault.Option.ClaimAsCVX, minAmountOut ); locker.lock(to, IERC20(CVX).balanceOf(address(this)), 0); } /// @notice Claim from the distributor, unstake to CVX and lock. /// @param index - claimer index /// @param account - claimer account /// @param amount - claim amount /// @param merkleProof - merkle proof for the claim /// @param minAmountOut - min amount of CVX expected /// @param to - address to lock on behalf of function claimFromDistributorAsCvxAndLock( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address to ) external notToZeroAddress(to) { distributor.claim(index, account, amount, merkleProof); claimFromVaultAsCvxAndLock(amount, minAmountOut, to); } /// @notice Deposit into the pounder from ETH /// @param minAmountOut - min amount of cvxCRV expected /// @param to - address to stake on behalf of function depositFromEth(uint256 minAmountOut, address to) external payable notToZeroAddress(to) { require(msg.value > 0, "cheap"); _depositFromEth(msg.value, minAmountOut, to); } /// @notice Internal function to deposit ETH to the pounder /// @param amount - amount of ETH /// @param minAmountOut - min amount of cvxCRV expected /// @param to - address to stake on behalf of function _depositFromEth( uint256 amount, uint256 minAmountOut, address to ) internal { uint256 _crvAmount = _swapEthToCrv(amount); uint256 _cvxCrvAmount = _swapCrvToCvxCrv( _crvAmount, address(this), minAmountOut ); IUnionVault(vault).deposit(to, _cvxCrvAmount); } /// @notice Deposit into the pounder from CRV /// @param minAmountOut - min amount of cvxCRV expected /// @param to - address to stake on behalf of function depositFromCrv( uint256 amount, uint256 minAmountOut, address to ) external notToZeroAddress(to) { IERC20(CRV_TOKEN).safeTransferFrom(msg.sender, address(this), amount); uint256 _cvxCrvAmount = _swapCrvToCvxCrv( amount, address(this), minAmountOut ); IUnionVault(vault).deposit(to, _cvxCrvAmount); } /// @notice Deposit into the pounder from any token via Uni interface /// @notice Use at your own risk /// @dev Zap contract needs approval for spending of inputToken /// @param amount - min amount of input token /// @param minAmountOut - min amount of cvxCRV expected /// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi /// @param inputToken - address of the token to swap from, needs to have an ETH pair on router used /// @param to - address to stake on behalf of function depositViaUniV2EthPair( uint256 amount, uint256 minAmountOut, address router, address inputToken, address to ) external notToZeroAddress(to) { require(router != address(0)); IERC20(inputToken).safeTransferFrom(msg.sender, address(this), amount); address[] memory _path = new address[](2); _path[0] = inputToken; _path[1] = WETH; IERC20(inputToken).safeApprove(router, 0); IERC20(inputToken).safeApprove(router, amount); IUniV2Router(router).swapExactTokensForETH( amount, 1, _path, address(this), block.timestamp + 1 ); _depositFromEth(address(this).balance, minAmountOut, to); } /// @notice Execute calls on behalf of contract /// (for instance to retrieve locked tokens) function execute( address _to, uint256 _value, bytes calldata _data ) external onlyOwner returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value: _value}(_data); return (success, result); } receive() external payable {} }
Deposit into the pounder from CRV minAmountOut - min amount of cvxCRV expected to - address to stake on behalf of
function depositFromCrv( uint256 amount, uint256 minAmountOut, address to ) external notToZeroAddress(to) { IERC20(CRV_TOKEN).safeTransferFrom(msg.sender, address(this), amount); uint256 _cvxCrvAmount = _swapCrvToCvxCrv( amount, address(this), minAmountOut ); IUnionVault(vault).deposit(to, _cvxCrvAmount); }
75,349
./full_match/1/0xd5324D3e0Fe24FaB2f05fd70b342aA209119E568/sources/contracts/PermissionedExecutors.sol
Only listed Executors can call this. Caution: there is no built-in coordination mechanism between the Executors. Only one Executor should be live at all times, lest they will incur tx collision costs.
function exec(TaskReceipt calldata _taskReceipt) external virtual onlyExecutors { _exec(_taskReceipt); }
16,475,762
./full_match/73799/0x6796B8a52B2CC672B14999d8B9939252E05F8080/sources/contracts/libraries/LibIssuer.sol
approveFor - Grants approval to the operator to transfer certificates owned by another wallet. certificateOwner address of the account owning the certificate to be transferred operator address of the account to be granted approval shouldBeApproved status of the approval to set when the approval is being set to true, `msg.sender` cannot be the same as `operator`/
function setApprovalFor( address certificateOwner, address operator, bool shouldBeApproved ) internal { if (shouldBeApproved && msg.sender == operator) { revert ForbiddenSelfApproval(msg.sender, certificateOwner); } ERC1155BaseStorage.layout().operatorApprovals[certificateOwner][operator] = shouldBeApproved; }
16,362,475
pragma solidity ^0.4.24; import "./tokens/NFToken.sol"; contract NFTDutchAuction { struct Auction { uint64 id; address seller; uint256 tokenId; uint128 startingPrice; // wei uint128 endingPrice; // wei uint64 duration; // seconds uint64 startedAt; // time } ERC721 public NFTContract; uint64 public auctionId; // max is 18446744073709551615 mapping (uint256 => Auction) internal tokenIdToAuction; mapping (uint64 => Auction) internal auctionIdToAuction; // TODO: are arrays of structs even possible? // use this for making auctions discoverable //mapping(address => Auction[]) internal ownerToAuction; //mapping(uint256 => uint256) internal auctionIdToOwnerIndex; event AuctionCreated(uint64 auctionId, uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionCancelled(uint64 auctionId, uint256 tokenId); event AuctionSuccessful(uint64 auctionId, uint256 tokenId, uint256 totalPrice, address winner); constructor(address _NFTAddress) public { NFTContract = ERC721(_NFTAddress); } // return ether that is sent to this contract function() external {} function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) public { // check storage requirements require(_startingPrice < 340282366920938463463374607431768211455); // 128 bits require(_endingPrice < 340282366920938463463374607431768211455); // 128 bits require(_duration <= 18446744073709551615); // 64 bits require(_duration >= 1 minutes); require(NFTContract.ownerOf(_tokenId) == msg.sender); Auction memory auction = Auction( uint64(auctionId), msg.sender, uint256(_tokenId), uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); tokenIdToAuction[_tokenId] = auction; auctionIdToAuction[auctionId] = auction; emit AuctionCreated( uint64(auctionId), uint256(_tokenId), uint256(auction.startingPrice), uint256(auction.endingPrice), uint256(auction.duration) ); auctionId++; } function getAuctionByAuctionId(uint64 _auctionId) public view returns ( uint64 id, address seller, uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = auctionIdToAuction[_auctionId]; require(auction.startedAt > 0); return ( auction.id, auction.seller, auction.tokenId, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } function getAuctionByTokenId(uint256 _tokenId) public view returns ( uint64 id, address seller, uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.startedAt > 0); return ( auction.id, auction.seller, auction.tokenId, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } function cancelAuctionByAuctionId(uint64 _auctionId) public { Auction storage auction = auctionIdToAuction[_auctionId]; require(auction.startedAt > 0); require(msg.sender == auction.seller); delete auctionIdToAuction[_auctionId]; delete tokenIdToAuction[auction.tokenId]; emit AuctionCancelled(_auctionId, auction.tokenId); } function cancelAuctionByTokenId(uint256 _tokenId) public { Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.startedAt > 0); require(msg.sender == auction.seller); delete auctionIdToAuction[auction.id]; delete tokenIdToAuction[_tokenId]; emit AuctionCancelled(auction.id, auction.tokenId); } function bid(uint256 _tokenId) public payable { Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.startedAt > 0); uint256 price = getCurrentPrice(auction); require(msg.value >= price); address seller = auction.seller; uint64 auctionId_temp = auction.id; delete tokenIdToAuction[_tokenId]; delete auctionIdToAuction[auction.id]; if (price > 0) { uint256 sellerProceeds = price; seller.transfer(sellerProceeds); } NFTContract.transferFrom(seller, msg.sender, _tokenId); emit AuctionSuccessful(auctionId_temp, _tokenId, price, msg.sender); } function getCurrentPriceByAuctionId(uint64 _auctionId) public view returns (uint256) { Auction storage auction = auctionIdToAuction[_auctionId]; return getCurrentPrice(auction); } function getCurrentPriceByTokenId(uint256 _tokenId) public view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; return getCurrentPrice(auction); } function getCurrentPrice(Auction storage _auction) internal view returns (uint256) { require(_auction.startedAt > 0); uint256 secondsPassed = 0; secondsPassed = now - _auction.startedAt; if (secondsPassed >= _auction.duration) { return _auction.endingPrice; } else { int256 totalPriceChange = int256(_auction.endingPrice) - int256(_auction.startingPrice); int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration); int256 currentPrice = int256(_auction.startingPrice) + currentPriceChange; return uint256(currentPrice); } } }
check storage requirements
function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) public { require(_duration >= 1 minutes); require(NFTContract.ownerOf(_tokenId) == msg.sender); Auction memory auction = Auction( uint64(auctionId), msg.sender, uint256(_tokenId), uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); tokenIdToAuction[_tokenId] = auction; auctionIdToAuction[auctionId] = auction; emit AuctionCreated( uint64(auctionId), uint256(_tokenId), uint256(auction.startingPrice), uint256(auction.endingPrice), uint256(auction.duration) ); auctionId++; }
12,642,221
// The tokens of this contract are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (https://creativecommons.org/licenses/by-nc-sa/4.0/) // SPDX-License-Identifier: CC-BY-NC-SA-4.0 pragma solidity ^0.8.0; import "./LadybugFinances.sol"; /** * @author WrightCode * @title Ladybug Minter * @dev Controls the information around minting and mint-related data */ contract LadybugMinter is LadybugFinances { uint private constant DROP_TIME_TOLERANCE = 1728000; // (60*60*24)*20 = 20 days uint private constant PRICE_TIME_TOLERANCE = 864000; // (60*60*24)*10 = 10 days bool private initialized; mapping(uint16 => uint16) private _randomized; /** * @dev Shuffle the deck, then premint to dev and owner accounts. */ function initialize() external onlyOwner { require(!initialized, "Contract already initialized"); initialized = true; // the development team will get a handful of preminted (but random, shuffled) nfts... for (uint i = 0; i < _RESERVED_LADYBUGS_DEVELOPMENT; i++) { _mintInternal(_developmentTeamAddress); } // ...as will the owner of the contract for (uint i = 0; i < _RESERVED_LADYBUGS_OWNER; i++) { _mintInternal(owner()); } // prepare the drops _initializeDrops(); } /** * @dev Mint the remaining bugs in drop to owner if "stalled out". * * The drop is considered stalled if the drop began more than DROP_TIME_TOLERANCE days ago, * the price is less than 0.01 ETH and has been at that price for more than PRICE_TIME_TOLERANCE days. * * The idea being that if no one is minting the ladybugs after the price has been lowered, * then the owner may mint them. * * Please do not let them stall out, these ladybugs need new greener gardens. * * In other words, I will not abandon my ladybugs. */ function mintStalledDropToOwner() external onlyOwner { (uint _index, bool _active, ) = _status(); require (_active, "Drop not active"); require (drops[_index].price <= 0.01 ether, "Price too high"); require (drops[_index].date < block.timestamp - DROP_TIME_TOLERANCE, "Drop not active long enough"); require (drops[_index].priceDate < block.timestamp - PRICE_TIME_TOLERANCE, "Price not active long enough"); for (uint i = _currentSupplyIndex(); i < drops[_index].startAtIndex + _TOKENS_PER_DROP; i++) { _mintStalled(owner()); } } /** * @dev Count the current number of ladybugs minted. */ function totalMinted() external view returns (uint) { return _currentSupplyIndex(); } /** * @dev Count the remaning, unminted ladybugs. */ function unminted() external view returns (uint) { return uint(_MAX_LADYBUGS) - _currentSupplyIndex(); } /** * @dev Mint the ERC 721 ladybug token, transfer it to the recipient. * The drop must be active and the payment must be above the specified drop price. */ function mint(address recipient) external payable returns (uint) { // if there's no active drop, error is thrown (uint _index, bool _active, ) = _status(); require (_active, "Drop not active"); require (msg.value >= drops[_index].price, "Offer lower than price"); return _mintInternal(recipient); } /** * @dev I believe this is necessary for OpenSea, there's no trailing slash. * The CID is the directory containing the nft metadata. */ function contractURI() public pure returns (string memory) { // todo https://docs.opensea.io/docs/contract-level-metadata // this is the pinata directory of the numbers metadata return "ipfs://QmP6wnMSYwzEQHWgBZobKF2drEr4GpE66w9jN1p3HDwhUe"; } /** * @dev Method used internally to construct the path to the token's metadata (json). * This is an ipfs uri with a trailing slash. */ function _baseURI() internal virtual override pure returns (string memory) { return "ipfs://QmP6wnMSYwzEQHWgBZobKF2drEr4GpE66w9jN1p3HDwhUe/"; } /** * @dev Mint the ERC 721 ladybug token, transfer it to the recipient. * * This is a very simple distribution of the bugs, they're not part of a great reveal, * we're not looking to game anyone, they simply want a good home with someone that'll * appreciate them. * * The goal is to mint the ladybugs in a non-sequential order. To do so, I'm adding a * little "randomness" on each mint. It's by no means perfect or unpredicatable, but * that's the scope of this project. * * Perhaps my next project, with a larger budget, will merit a more challenging and * sophisticted mint. That would be a lot of fun to work on. * * Until then, enjoy the bugs as they are, they're ready to fly. */ function _mintInternal(address recipient) internal returns (uint) { // the tokens are 1.._MAX_LADYBUGS (i.e. not zero-based) uint16 _index = uint16(_currentSupplyIndex() + 1); uint newItemId; // check if this index is part of the mapping if (_randomized[_index] != 0) { newItemId = _randomized[_index]; // it would be nice to remove the entry from _randomized after retrieving the value, // but the gas was too expensive and so i chose not not, on behalf of the minter } else { uint16 n = uint16(_index + uint256(keccak256(abi.encodePacked(block.timestamp))) % (_MAX_LADYBUGS - _currentSupplyIndex())); // if the random number is not already holding a swap, use it ... if (_randomized[n] == 0 && _index != n) { _randomized[n] = _index; newItemId = n; } else { // ... else just use the index, the random swap (n) already has a value newItemId = _index; } } _mint(recipient, newItemId); // increment the supply counter _incrementCurrentSupplyIndex(); return newItemId; } /** * @dev Mint the stalled-out ERC 721 ladybug tokens, transfer it to the recipient. * Gas is expensive in this process, so we'll look at any previously "randomized" * elements and use them, otherwise, we'll just go in order to reduce gas prices. */ function _mintStalled(address recipient) internal returns (uint) { // get the mint id from the shuffled array (it's zero based) uint16 _index = uint16(_currentSupplyIndex() + 1); uint newItemId; // check if this index is part of the mapping if (_randomized[_index] != 0) { newItemId = _randomized[_index]; // it would be nice to remove the entry from _randomized after retrieving the value, // but the gas was too expensive and so i chose not not, on behalf of the minter } else { // ... else just use the index, it's too expensive in gas, to randomize here newItemId = _index; } _mint(recipient, newItemId); // increment the supply counter _incrementCurrentSupplyIndex(); return newItemId; } } // The tokens of this contract are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (https://creativecommons.org/licenses/by-nc-sa/4.0/) // SPDX-License-Identifier: CC-BY-NC-SA-4.0 pragma solidity ^0.8.0; import "./LadybugDrops.sol"; /** * @author WrightCode * @title Ladybug Finances * @dev Encapsulate the financial side of the contract */ contract LadybugFinances is LadybugDrops {//, RoyaltiesV2Impl { bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; uint16 internal constant _DEFAULT_ROYALTY_VALUE = 250; // 2.5% uint16 internal constant _MAX_ROYALTY_VALUE = 450; // 4.5% address internal _royaltyRecipient; uint16 private _royaltyBasis = _DEFAULT_ROYALTY_VALUE; /** * @dev Sets initial royalty recipient to be the owner() */ constructor() { _royaltyRecipient = owner(); } /** * @dev Modifier that restricts how high the royalties can be. */ modifier royaltiesConstraint(uint16 basis) { // restrict the royalties to 4.5% at the most require(_MAX_ROYALTY_VALUE >= basis, "Royalty basis too high"); _; } /** * @dev ERC-2981 interface to retriee royalty information by any service that adheres to the standard and pays royalties. * Some implementations use per-tokenId configurations, but this implementation uses the same recipient and royalty basis * for all tokens. */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { return (payable(_royaltyRecipient), uint((_salePrice * _royaltyBasis)/10000)); } /** * @dev View the royalty recipient and basis values. */ function getLadybugRoyaltyInfo() external view returns (address receiver, uint16 basis) { return (_royaltyRecipient, _royaltyBasis); } /** * @dev Allows owner to change the royalties and recipient of royalties. */ function setLadybugRoyaltyInfo(address _recipient, uint16 _basis) external royaltiesConstraint(_basis) onlyOwner { _royaltyRecipient = _recipient; _royaltyBasis = _basis; } /** * @dev Display the balance of funds in the contract, onlyOwner. */ function balanceInContract() external view onlyOwner returns(uint) { return address(this).balance; } /** * @dev Allows owner to transfer all funds from contract, effectively paying oneself. */ function withdrawAll() external onlyOwner returns(uint) { address _owner = owner(); uint balance = address(this).balance; payable(_owner).transfer(balance); return balance; } /** * @dev Allows owner to transfer some of the funds from contract, effectively paying oneself. */ function withdraw(uint balance) external onlyOwner returns(uint) { address _owner = owner(); require(balance <= address(this).balance, "Balance too high"); payable(_owner).transfer(balance); return balance; } /** * @dev Supports Interface for ERC-2981 */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { if (interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(interfaceId); } } // The tokens of this contract are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (https://creativecommons.org/licenses/by-nc-sa/4.0/) // SPDX-License-Identifier: CC-BY-NC-SA-4.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /** * @author WrightCode * @title Ladybug Factory * @dev The base-layer data for the Ladybug ERC721 tokens. * * This is my first implementation of a smart contract in Solidity. It's gone thru quite * a few iterations as I learn my way around the system, gas expenses, and fine tuning the * "expectations" of the contract. * * I do consider this somehwat of a "reference implementation". It's far from * perfect and the trade-offs made were to enjoy the process, stay well within "budget", * yet provide as fair a minting process as the scope allowed. * * I could have easily continued down the rabbit hole of tuning and features, at the expense * of my own ETH and time, but at some point the goal remained: * * A) Share the artwork, the ladybugs are ready to fly * B) Deliever a contract for talking points with future projects. * C) Learn and have fun doing so. * * If you decide to participate in the minting process or otherwise engage in this project * I hope you do so for fun and enjoy the bugs. * */ contract LadybugFactory is Ownable, ERC721 { address internal _developmentTeamAddress = 0x3254C065f85167003F165E134A391a6ec2c26279; using Counters for Counters.Counter; Counters.Counter private _tokenIds; uint16 internal constant _MAX_LADYBUGS = 1120; uint16 internal constant _RESERVED_LADYBUGS_DEVELOPMENT = 64; uint16 internal constant _RESERVED_LADYBUGS_OWNER = 32; uint16 internal constant _RESERVED_LADYBUGS = _RESERVED_LADYBUGS_DEVELOPMENT + _RESERVED_LADYBUGS_OWNER; uint16 internal constant _TOKENS_PER_DROP = (_MAX_LADYBUGS - _RESERVED_LADYBUGS) / 4; struct Drop { uint256 price; // needs to be in wei (eth * 10^18) uint256 date; // uint in seconds since epoch uint256 priceDate; // date the current price went into effect uint16 startAtIndex; // the ladybugs index at which this drop would begin } /** There will be four drops. Price & date can be configured by owner. The next four will each be (_MAX_LADYBUGS - _RESERVED_LADYBUGS)/4 ladybugs, with a configurable drop date and price. */ Drop[4] internal drops; /** * @dev There are four drops, 1-4 in the drops array. */ constructor() ERC721("Ladybug Power", "LADYBUG") { } /** * @dev The total supply of all ladybug tokens. */ function totalSupply() external pure returns (uint16) { return _MAX_LADYBUGS; } /** * @dev Constant, number of tokens per drop. */ function tokensPerDrop() external pure returns (uint16) { return _TOKENS_PER_DROP; } /** * @dev Return array of ladybug token Ids owned by the address. */ function getLadybugIdsByOwner(address bugOwner) external view returns(uint[] memory) { uint[] memory result = new uint[](balanceOf(bugOwner)); uint16 counter = 0; for (uint16 i = 1; i <= _MAX_LADYBUGS; i++) { if (_exists(i) && ownerOf(i) == bugOwner) { result[counter] = i; counter++; } } return result; } /** * @dev Increment the current supply index by one. */ function _incrementCurrentSupplyIndex() internal { _tokenIds.increment(); } /** * @dev The index of the next mint from the supply. Aka, current mint position. */ function _currentSupplyIndex() internal view returns (uint) { return _tokenIds.current(); } } // The tokens of this contract are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (https://creativecommons.org/licenses/by-nc-sa/4.0/) // SPDX-License-Identifier: CC-BY-NC-SA-4.0 pragma solidity ^0.8.0; import "./LadybugFactory.sol"; /** * @author WrightCode * @title Ladybug Drops * @dev Encapsulates the data surrounding the 4 ladybug "drops". */ contract LadybugDrops is LadybugFactory { /** * @dev Modifier that prevents a date change once a drop has started. */ modifier dropNotStarted(uint8 index, uint date) { // the drop we're updating can't be starting within the hour. require(drops[index].date == 0 || drops[index].date > block.timestamp + 3600, "Drop starting too soon"); // the _date value must be two hours out from now require(date > block.timestamp + 7200, "New start date too close"); _; } /** * @dev Modifier to ensure a price change on an active drop will be a descrease. * This contract does not allow a price increase on active drops. */ modifier priceNotIncreased(uint8 index, uint price) { // the new price must be lower require(drops[index].price > price, "Price cannot increase"); // price drop must be for current or future drop require(index >= _currentDropIndex(), "Drop has already completed"); _; } /** * @dev Return an array of all the drops. */ function getDrops() external view returns (Drop[] memory) { Drop[] memory results = new Drop[](drops.length); for (uint i = 0; i < drops.length; i++) { results[i] = drops[i]; } return results; } /** * @dev Update the price and date of non-active drops only. */ function updateDrop(uint8 index, uint price, uint date) external dropNotStarted(index, date) onlyOwner { drops[index].price = price; drops[index].date = date; // the price will go into effect on date drops[index].priceDate = date; } /** * @dev Decrease the price of an active drop. Useful if drops "stall out". * Why would I do this? Well, I am not convinced the world will love my ladybugs as * much as I love my ladybugs, and I am okay with this. Art is subjective. * So if this proves true, then I want the ability to end the mint, and * re-evaluate my distribution plan. I will not abandon my ladybugs. */ function dropPrice(uint8 index, uint price) external priceNotIncreased(index, price) onlyOwner { drops[index].price = price; // the price will go into effect now, if the drops[index].date < block timestamp; if (drops[index].date < block.timestamp) { // drop is active, so set new priceDate drops[index].priceDate = block.timestamp; } } /** * @dev Return the current drop index and whether it's active or not. */ function status() external view returns (uint index, bool active, bool complete) { return _status(); } function _initializeDrops() internal onlyOwner { uint16 startAtIndex = _RESERVED_LADYBUGS; for (uint8 i = 0; i < drops.length; i++) { drops[i].startAtIndex = startAtIndex; startAtIndex += _TOKENS_PER_DROP; } } /** * @dev Returns the current drop (0-3) in which the next ladybug would be minted. * This does not take the drop date into account, so it might not be an active drop. */ function _currentDropIndex() internal view returns (uint8) { for (uint i = drops.length - 1; i >= 0; i--) { if (_currentSupplyIndex() >= drops[i].startAtIndex) { return uint8(i); } } // should never reach this line of code revert("Error finding drop index"); } /** * @dev Same call as status, but this one is 'internal'. Breaking out the two * is being done for gas efficiency, when status is needed internally. */ function _status() internal view returns (uint index, bool active, bool complete) { uint8 currentIndex = _currentDropIndex(); bool isComplete = _currentSupplyIndex() >= _MAX_LADYBUGS; // a drop is active if all are not complete, the date is non-zero, // and the blockchain time is greater than the drop date. bool isActive = isComplete != true && drops[currentIndex].date != 0 && drops[currentIndex].date <= block.timestamp; return (currentIndex, isActive, isComplete); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Increment the current supply index by one./
function _incrementCurrentSupplyIndex() internal { _tokenIds.increment(); }
10,276,059
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface 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; } /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SignedSafeMath { /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { return a / b; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { return a - b; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { return a + b; } } // 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; } } } /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 5; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @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); } } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } /// @title Dividend-Paying Token Optional Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev OPTIONAL functions for a dividend-paying token contract. interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns(uint256); } /// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract. interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); } /// @title Dividend-Paying Token /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SignedSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) { } /// @dev Distributes dividends whenever ether is paid to this contract. receive() external payable { distributeDividends(); } /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividends() public override payable { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed = totalDividendsDistributed.add(msg.value); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success,) = user.call{value: _withdrawableDividend, gas: 3000}(""); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256() .add(magnifiedDividendCorrections[_owner]).toUint256() / magnitude; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256() ); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } } contract SUNDividendTracker is DividendPayingToken, Ownable { using SafeMath for uint256; using SignedSafeMath for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public immutable minimumTokenBalanceForDividends; event ExcludeFromDividends(address indexed account); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("SUN_Dividend_Tracker", "SUN_Dividend_Tracker") { claimWait = 3600; minimumTokenBalanceForDividends = 10000 * (10**5); //must hold 10000+ tokens } function _transfer(address, address, uint256) internal pure override { require(false, "SUN_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require(false, "SUN_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main SUN contract."); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludeFromDividends(account); } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "SUN_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "SUN_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if(index >= 0) { if(uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { if(index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if(lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if(excludedFromDividends[account]) { return; } if(newBalance >= minimumTokenBalanceForDividends) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if(numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while(gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if(_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if(canAutoClaim(lastClaimTimes[account])) { if(processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if(gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if(amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } } contract SafeToken is Ownable { address payable safeManager; constructor() { safeManager = payable(msg.sender); } function setSafeManager(address payable _safeManager) public onlyOwner { safeManager = _safeManager; } function withdraw(address _token, uint256 _amount) external { require(msg.sender == safeManager); IERC20(_token).transfer(safeManager, _amount); } function withdrawBNB(uint256 _amount) external { require(msg.sender == safeManager); safeManager.transfer(_amount); } } contract LockToken is Ownable { bool public isOpen = false; mapping(address => bool) private _whiteList; modifier open(address from, address to) { require(isOpen || _whiteList[from] || _whiteList[to], "Not Open"); _; } constructor() { _whiteList[msg.sender] = true; _whiteList[address(this)] = true; } function openTrade() external onlyOwner { isOpen = true; } function includeToWhiteList(address[] memory _users) external onlyOwner { for(uint8 i = 0; i < _users.length; i++) { _whiteList[_users[i]] = true; } } } contract SUN is ERC20, Ownable, SafeToken, LockToken { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; SUNDividendTracker public dividendTracker; uint256 public maxSellTransactionAmount = 1000000000000000000 * (10**5); uint256 public swapTokensAtAmount = 200000000000000 * (10**5); uint256 public ETHRewardFee; uint256 public liquidityFee; uint256 public totalFees; uint256 public extraFeeOnSell; uint256 public marketingFee; address payable public marketingWallet; // use by default 300,000 gas to process auto-claiming dividends uint256 public gasForProcessing = 300000; // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping(address => bool) private _isExcludedFromMaxTx; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensIntoLiqudity, uint256 ethReceived ); event SendDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } function setFee(uint256 _ethRewardFee, uint256 _liquidityFee, uint256 _marketingFee) public onlyOwner { ETHRewardFee = _ethRewardFee; liquidityFee = _liquidityFee; marketingFee = _marketingFee; totalFees = ETHRewardFee.add(liquidityFee).add(marketingFee); // total fee transfer and buy } function setExtraFeeOnSell(uint256 _extraFeeOnSell) public onlyOwner { extraFeeOnSell = _extraFeeOnSell; // extra fee on sell } function setMaxSelltx(uint256 _maxSellTxAmount) public onlyOwner { maxSellTransactionAmount = _maxSellTxAmount; } function setMarketingWallet(address payable _newMarketingWallet) public onlyOwner { marketingWallet = _newMarketingWallet; } constructor() ERC20("Rising Sun", "SUN") { ETHRewardFee = 5; liquidityFee = 3; extraFeeOnSell = 0; // extra fee on sell marketingFee = 5; marketingWallet = payable(0xaec4FA7E09B3916C1938eE49e1CB8CdB4c38a8Cf); totalFees = ETHRewardFee.add(liquidityFee).add(marketingFee); // total fee transfer and buy dividendTracker = new SUNDividendTracker(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); dividendTracker.excludeFromDividends(0x000000000000000000000000000000000000dEaD); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(address(this), true); // exclude from max tx _isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; _isExcludedFromMaxTx[marketingWallet] = true; /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), 100000000000000000000 * (10**5)); } receive() external payable { } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "SUN: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); } function excludeFromFees(address account, bool excluded) public onlyOwner { require(_isExcludedFromFees[account] != excluded, "SUN: Account is already the value of 'excluded'"); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setExcludeFromMaxTx(address _address, bool value) public onlyOwner { _isExcludedFromMaxTx[_address] = value; } function setExcludeFromAll(address _address) public onlyOwner { _isExcludedFromMaxTx[_address] = true; _isExcludedFromFees[_address] = true; dividendTracker.excludeFromDividends(_address); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "SUN: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function setSWapToensAtAmount(uint256 _newAmount) public onlyOwner { swapTokensAtAmount = _newAmount; } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "SUN: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue >= 200000 && newValue <= 500000, "SUN: gasForProcessing must be between 200,000 and 500,000"); require(newValue != gasForProcessing, "SUN: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function isExcludedFromMaxTx(address account) public view returns(bool) { return _isExcludedFromMaxTx[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(payable(msg.sender), false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } //this will be used to exclude from dividends the presale smart contract address function excludeFromDividends(address account) external onlyOwner { dividendTracker.excludeFromDividends(account); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _transfer( address from, address to, uint256 amount ) open(from, to) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromMaxTx[from]) && (!_isExcludedFromMaxTx[to])){ require(amount <= maxSellTransactionAmount, "Sell transfer amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && !automatedMarketMakerPairs[from] && swapAndLiquifyEnabled ) { swapAndLiquify(contractTokenBalance); } // if any account belongs to _isExcludedFromFee account then remove the fee if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 fees = (amount*totalFees)/100; uint256 extraFee; if(automatedMarketMakerPairs[to]) { extraFee =(amount*extraFeeOnSell)/100; fees=fees+extraFee; } amount = amount-fees; super._transfer(from, address(this), fees); // get total fee first } super._transfer(from, to, amount); try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {} if(!inSwapAndLiquify) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // take liquidity fee, keep a half token // halfLiquidityToken = totalAmount * (liquidityFee/2totalFee) uint256 tokensToAddLiquidityWith = contractTokenBalance.div(totalFees.mul(2)).mul(liquidityFee); // swap the remaining to BNB uint256 toSwap = contractTokenBalance-tokensToAddLiquidityWith; // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForBnb(toSwap, address(this)); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered uint256 deltaBalance = address(this).balance-initialBalance; // take worthy amount bnb to add liquidity // worthyBNB = deltaBalance * liquidity/(2totalFees - liquidityFee) uint256 bnbToAddLiquidityWith = deltaBalance.mul(liquidityFee).div(totalFees.mul(2).sub(liquidityFee)); // add liquidity to uniswap addLiquidity(tokensToAddLiquidityWith, bnbToAddLiquidityWith); // worthy marketing fee uint256 marketingAmount = deltaBalance.sub(bnbToAddLiquidityWith).div(totalFees.sub(liquidityFee)).mul(marketingFee); marketingWallet.transfer(marketingAmount); uint256 dividends = address(this).balance; (bool success,) = address(dividendTracker).call{value: dividends}(""); if(success) { emit SendDividends(toSwap-tokensToAddLiquidityWith, dividends); } emit SwapAndLiquify(tokensToAddLiquidityWith, deltaBalance); } function swapTokensForBnb(uint256 tokenAmount, address _to) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); if(allowance(address(this), address(uniswapV2Router)) < tokenAmount) { _approve(address(this), address(uniswapV2Router), ~uint256(0)); } // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, _to, block.timestamp ); } function swapAndSendBNBToMarketing(uint256 tokenAmount) private { swapTokensForBnb(tokenAmount, marketingWallet); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } }
Internal function that transfer tokens from one address to another. Update magnifiedDividendCorrections to keep dividends unchanged. from The address to transfer from. to The address to transfer to. value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); }
73,002
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.3; /* ▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓ ▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒ ▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░ ▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░ ░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒ ░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████ ▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒ ▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄ ▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒ ▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒ ░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░ ░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ Crazy Clowns Insane Asylum 2021, V1.1 https://ccia.io */ import '@openzeppelin/contracts/utils/Counters.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import './NFTExtension.sol'; import './Metadata.sol'; import './interfaces/INFTStaking.sol'; contract CrazyClown is Metadata, NFTExtension { using Counters for Counters.Counter; using Strings for uint256; // Counter service to determine tokenId Counters.Counter private _tokenIds; // General details uint256 public constant maxSupply = 9696; // Public sale details uint256 public price = 0.05 ether; // Public sale price uint256 public publicSaleTransLimit = 10; // Public sale limit per transaction uint256 public publicMintLimit = 500; // Public mint limit per Wallet bool private _publicSaleStarted; // Flag to enable public sale mapping(address => uint256) public mintListPurchases; // Presale sale details uint256 public preSalePrice = 0.04 ether; uint256 public preSaleMintLimit = 10; // Presale limit per wallet bool public preSaleLive = false; Counters.Counter private preSaleAmountMinted; mapping(address => uint256) public preSaleListPurchases; mapping(address => bool) public preSaleWhitelist; // Reserve details for founders / gifts uint256 private reservedSupply = 196; // Metadata details string _baseTokenURI; string _contractURI; //NFTStaking interface INFTStaking public nftStaking; // Whitelist contracts address[] contractWhitelist; mapping(address => uint256) contractWhitelistIndex; constructor( string memory name, string memory symbol, string memory baseURI, string memory contractStoreURI, address utilityToken, address _proxyRegistryAddress ) ERC721(name, symbol) Metadata(utilityToken, maxSupply) { _publicSaleStarted = false; _baseTokenURI = baseURI; _contractURI = contractStoreURI; admins[_msgSender()] = true; proxyRegistryAddress = _proxyRegistryAddress; } // Public sale functions modifier whenPublicSaleStarted() { require(_publicSaleStarted, 'Sale has not yet started'); _; } function flipPublicSaleStarted() external onlyOwner { _publicSaleStarted = !_publicSaleStarted; } function saleStarted() public view returns (bool) { return _publicSaleStarted; } function mint(uint256 _nbTokens, bool allowStaking) external payable override { // Presale minting require(_publicSaleStarted || preSaleLive, 'Sale has not yet started'); uint256 _currentSupply = _tokenIds.current(); if (!_publicSaleStarted && preSaleLive) { require(preSaleWhitelist[msg.sender] || isWhitelistContractHolder(msg.sender), 'Not on presale whitelist'); require(preSaleListPurchases[msg.sender] + _nbTokens <= preSaleMintLimit, 'Exceeded presale allowed buy limit'); require(preSalePrice * _nbTokens <= msg.value, 'Insufficient ETH'); for (uint256 i = 0; i < _nbTokens; i++) { preSaleAmountMinted.increment(); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); preSaleListPurchases[msg.sender]++; tokenMintDate[newItemId] = block.timestamp; _safeMint(msg.sender, newItemId); if (allowStaking) { nftStaking.stake(address(this), newItemId, msg.sender); } } } else if (_publicSaleStarted) { // Public sale minting require(_nbTokens <= publicSaleTransLimit, 'You cannot mint that many NFTs at once'); require(_currentSupply + _nbTokens <= maxSupply - reservedSupply, 'Not enough Tokens left.'); require(mintListPurchases[msg.sender] + _nbTokens <= publicMintLimit, 'Exceeded sale allowed buy limit'); require(_nbTokens * price <= msg.value, 'Insufficient ETH'); for (uint256 i; i < _nbTokens; i++) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); mintListPurchases[msg.sender]++; tokenMintDate[newItemId] = block.timestamp; _safeMint(msg.sender, newItemId); if (allowStaking) { setApprovalForAll(address(nftStaking), true); nftStaking.stake(address(this), newItemId, msg.sender); } } } } /** * called after deployment so that the contract can get NFT staking contracts * @param _nftStaking the address of the NFTStaking */ function setNFTStaking(address _nftStaking) external onlyOwner { nftStaking = INFTStaking(_nftStaking); } function setPublicMintLimit(uint256 limit) external onlyOwner { publicMintLimit = limit; } function setPublicSaleTransLimit(uint256 limit) external onlyOwner { publicSaleTransLimit = limit; } // Make it possible to change the price: just in case function setPrice(uint256 _newPrice) external onlyOwner { price = _newPrice; } function getPrice() public view returns (uint256) { return price; } // Pre sale functions modifier whenPreSaleLive() { require(preSaleLive, 'Presale has not yet started'); _; } modifier whenPreSaleNotLive() { require(!preSaleLive, 'Presale has already started'); _; } function setPreSalePrice(uint256 _newPreSalePrice) external onlyOwner whenPreSaleNotLive { preSalePrice = _newPreSalePrice; } // Add an array of wallet addresses to the presale white list function addToPreSaleList(address[] calldata entries) external onlyOwner { for (uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), 'NULL_ADDRESS'); require(!preSaleWhitelist[entry], 'DUPLICATE_ENTRY'); preSaleWhitelist[entry] = true; } } // Remove an array of wallet addresses to the presale white list function removeFromPreSaleList(address[] calldata entries) external onlyOwner { for (uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), 'NULL_ADDRESS'); preSaleWhitelist[entry] = false; } } function isPreSaleApproved(address addr) external view returns (bool) { return preSaleWhitelist[addr]; } function flipPreSaleStatus() external onlyOwner { preSaleLive = !preSaleLive; } function getPreSalePrice() public view returns (uint256) { return preSalePrice; } function setPreSaleMintLimit(uint256 _newPresaleMintLimit) external onlyOwner { preSaleMintLimit = _newPresaleMintLimit; } // Reserve functions // Owner to send reserve NFT to address function sendReserve(address _receiver, uint256 _nbTokens) public onlyAdmin { uint256 _currentSupply = _tokenIds.current(); require(_currentSupply + _nbTokens <= maxSupply - reservedSupply, 'Not enough supply left'); require(_nbTokens <= reservedSupply, 'That would exceed the max reserved'); for (uint256 i; i < _nbTokens; i++) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); tokenMintDate[newItemId] = block.timestamp; _safeMint(_receiver, newItemId); } reservedSupply = reservedSupply - _nbTokens; } function getReservedLeft() public view whenPublicSaleStarted returns (uint256) { return reservedSupply; } // Make it possible to change the reserve only if sale not started: just in case function setReservedSupply(uint256 _newReservedSupply) external onlyOwner { reservedSupply = _newReservedSupply; } // Storefront metadata // https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return _contractURI; } function setContractURI(string memory _URI) external onlyOwner { _contractURI = _URI; } function setBaseURI(string memory _URI) external onlyOwner { _baseTokenURI = _URI; } function _baseURI() internal view override(ERC721) returns (string memory) { return _baseTokenURI; } // General functions & helper functions // Helper to list all the NFTs of a wallet function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function withdraw(address _receiver) public onlyOwner { uint256 _balance = address(this).balance; require(payable(_receiver).send(_balance)); } function burn(uint256 tokenId) external override onlyAdmin { _burn(tokenId); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } function addContractToWhitelist(address _contract) external onlyOwner { contractWhitelist.push(_contract); contractWhitelistIndex[_contract] = contractWhitelist.length - 1; } function removeContractFromWhitelist(address _contract) external onlyOwner { uint256 lastIndex = contractWhitelist.length - 1; address lastContract = contractWhitelist[lastIndex]; uint256 contractIndex = contractWhitelistIndex[_contract]; contractWhitelist[contractIndex] = lastContract; contractWhitelistIndex[lastContract] = contractIndex; if (contractWhitelist.length > 0) { contractWhitelist.pop(); delete contractWhitelistIndex[_contract]; } } function isWhitelistContractHolder(address user) internal view returns (bool) { for (uint256 index = 0; index < contractWhitelist.length; index++) { uint256 balanceOfSender = IERC721(contractWhitelist[index]).balanceOf(user); if (balanceOfSender > 0) return true; } return false; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(tokenId <= _tokenIds.current(), 'Token does not exist'); if (PublicRevealStatus) return super.tokenURI(tokenId); else return placeHolderURI; } function isWhitelisted() public view returns (bool) { return (preSaleWhitelist[msg.sender] || isWhitelistContractHolder(msg.sender)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.3; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol'; import '@openzeppelin/contracts/utils/Counters.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } abstract contract NFTExtension is ERC721URIStorage, Ownable { using Counters for Counters.Counter; mapping(address => bool) internal admins; Counters.Counter internal _totalSupply; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; modifier onlyAdmin() { require(admins[_msgSender()], 'Caller is not the admin'); _; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return super.isApprovedForAll(_owner, _operator); } // Function to grant admin role function addAdminRole(address _address) external onlyOwner { admins[_address] = true; } // Function to revoke admin role function revokeAdminRole(address _address) external onlyOwner { admins[_address] = false; } function hasAdminRole(address _address) external view returns (bool) { return admins[_address]; } function _burn(uint256 tokenId) internal override(ERC721URIStorage) { super._burn(tokenId); } // Support Interface /* function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); } */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) { require(index < balanceOf(owner), 'ERC721Enumerable: owner index out of bounds'); return _ownedTokens[owner][index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _totalSupply.increment(); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _totalSupply.decrement(); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } function totalSupply() public view returns (uint256) { return _totalSupply.current(); } // function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {} function burn(uint256 tokenId) external virtual {} function mint(uint256 _nbTokens, bool nftStaking) external payable virtual {} function evolve_mint(address _user) external virtual returns (uint256) {} } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.3; pragma experimental ABIEncoderV2; import { Base64 } from 'base64-sol/base64.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import './interfaces/IBalloonToken.sol'; contract Metadata is Ownable { using Strings for uint256; // utility token IBalloonToken public utilityToken; // Utility Token Fee to update Name, Bio uint256 public _changeNameFee = 10 * 10**18; uint256 public _changeBioFee = 25 * 10**18; uint256 TotalSupply; // Image Placeholder URI string public placeHolderURI; // Public Reveal Status bool public PublicRevealStatus = false; struct Meta { string name; string description; } // Mapping from tokenId to meta struct mapping(uint256 => Meta) metaList; // Mapping from tokenId to boolean to make sure name is updated. mapping(uint256 => bool) _isNameUpdated; // Mapping from tokenId to boolean to make sure bio is updated. mapping(uint256 => bool) _isBioUpdated; // Mapping from token Id to mint date mapping(uint256 => uint256) tokenMintDate; constructor(address _utilityToken, uint256 _totalSupply) { utilityToken = IBalloonToken(_utilityToken); TotalSupply = _totalSupply; } function changeName(uint256 _tokenId, string memory _name) external { Meta storage _meta = metaList[_tokenId]; _meta.name = _name; _isNameUpdated[_tokenId] = true; utilityToken.burn(msg.sender, _changeNameFee); } function changeBio(uint256 _tokenId, string memory _bio) external { Meta storage _meta = metaList[_tokenId]; _meta.description = _bio; _isBioUpdated[_tokenId] = true; utilityToken.burn(msg.sender, _changeBioFee); } function getTokenName(uint256 _tokenId) public view returns (string memory) { return metaList[_tokenId].name; } function getTokenBio(uint256 _tokenId) public view returns (string memory) { return metaList[_tokenId].description; } function setPlaceholderURI(string memory uri) public onlyOwner { placeHolderURI = uri; } function togglePublicReveal() external onlyOwner { PublicRevealStatus = !PublicRevealStatus; } function _getTokenMintDate(uint256 tokenId) internal view returns (uint256) { return tokenMintDate[tokenId]; } function setChangeNameFee(uint256 _fee) external onlyOwner { _changeNameFee = _fee; } function setChangeBioFee(uint256 _fee) external onlyOwner { _changeBioFee = _fee; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.3; /* ▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓ ▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒ ▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░ ▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░ ░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒ ░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████ ▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒ ▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄ ▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒ ▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒ ░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░ ░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ Crazy Clowns Insane Asylum 2021, V1.1 https://ccia.io */ interface INFTStaking { function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function NFTTokens(address) external view returns (address); function addEvolvePath( address from_address, address to_address, bool burn_original, address fee_contract, uint256 evolve_fee ) external; function addNftReward(address contract_address, uint256 reward_per_block_day) external; function blockPerDay() external view returns (uint256); function claimAll(address _tokenAddress) external; function claimReward( address _user, address _tokenAddress, uint256 _tokenId ) external; function dailyReward(address) external view returns (uint256); function deleteEvolvePath(address from_address) external; function emergencyUnstake(address _tokenAddress, uint256 _tokenId) external; function evolvePath(address original_nft_address, uint256 token_id) external; function evolvePathList(address) external view returns ( address to_address, bool burn_original, address fee_contract, uint256 evolve_fee ); function getRoleAdmin(bytes32 role) external view returns (bytes32); function getStakedTokens(address _user, address _tokenAddress) external view returns (uint256[] memory tokenIds); function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function pendingReward( address _user, address _tokenAddress, uint256 _tokenId ) external view returns (uint256); function removeNftReward(address contract_address) external; function renounceRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function rewardsToken() external view returns (address); function stake( address _tokenAddress, uint256 _tokenId, address _account ) external; function supportsInterface(bytes4 interfaceId) external view returns (bool); function tokenOwner(address, uint256) external view returns (address); function unstake(address _tokenAddress, uint256 _tokenId) external; function updateBlockPerDay(uint256 _blockPerDay) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.3; /* ▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓ ▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒ ▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░ ▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░ ░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒ ░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████ ▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒ ▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄ ▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒ ▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒ ░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░ ░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ Crazy Clowns Insane Asylum 2021, V1.1 https://ccia.io */ interface IBalloonToken { function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function addMinterRole(address _address) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function burn(address account, uint256 amount) external; // function checkpoints ( address account, uint32 pos ) external view returns ( tuple ); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external; function delegates(address account) external view returns (address); function getPastTotalSupply(uint256 blockNumber) external view returns (uint256); function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); function getRoleAdmin(bytes32 role) external view returns (bytes32); function getVotes(address account) external view returns (uint256); function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function mint(address to, uint256 amount) external; function name() external view returns (string memory); function nonces(address owner) external view returns (uint256); function numCheckpoints(address account) external view returns (uint32); // function owner ( ) external view returns ( address ); function pause() external; function paused() external view returns (bool); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function renounceOwnership() external; function renounceRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function supportsInterface(bytes4 interfaceId) external view returns (bool); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function transferOwnership(address newOwner) external; function unpause() external; }
called after deployment so that the contract can get NFT staking contracts _nftStaking the address of the NFTStaking/
function setNFTStaking(address _nftStaking) external onlyOwner { nftStaking = INFTStaking(_nftStaking); }
1,671,633
pragma solidity ^0.4.23; import "../DaoClient.sol"; import "../IDaoBase.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; contract SimpleICO is DaoClient, Ownable { using SafeMath for uint256; address public tokenAddress; uint256 public rate; uint256 public weiRaised; uint256 public minPurchase; uint256 public maxPurchase; uint256 public softCap; uint256 public hardCap; uint256 public startDate; uint256 public endDate; bool public stopped; bool public paused; mapping(address => uint256) private deposits; mapping(address => bool) private isWhitelisted; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); modifier onlyWhileOpen() { require(block.timestamp >= startDate && block.timestamp <= endDate && weiRaised <= hardCap && !stopped); _; } modifier onlyAfterFail() { require((block.timestamp >= endDate && weiRaised < softCap) || stopped); _; } modifier onlyAfterSuccess() { require(block.timestamp >= endDate && weiRaised >= softCap); _; } modifier whenNotPaused() { require(!paused); _; } constructor( uint256 _rate, address _tokenAddress, IDaoBase _daoBase, uint256 _minPurchase, uint256 _maxPurchase, uint256 _startDate, uint256 _endDate, uint256 _softCap, uint256 _hardCap ) public DaoClient(_daoBase) { require(_rate > 0); require(_tokenAddress != address(0)); require(_endDate > block.timestamp); rate = _rate; tokenAddress = _tokenAddress; minPurchase = _minPurchase; maxPurchase = _maxPurchase; startDate = _startDate; endDate = _endDate; softCap = _softCap; hardCap = _hardCap; } function () external payable { buyTokens(msg.sender); } /** * @notice This function should be called only when ICO open and not paused * @param _beneficiary account which gets tokens */ function buyTokens(address _beneficiary) onlyWhileOpen whenNotPaused public payable { require (msg.value >= minPurchase && msg.value <= maxPurchase); require (msg.value + weiRaised <= hardCap); require(msg.value != 0); uint256 weiAmount = msg.value; deposits[msg.sender] = deposits[msg.sender].add(weiAmount); emit Deposited(msg.sender, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); daoBase.issueTokens(tokenAddress, _beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); } /** * @notice This function should be called only when ICO open and not paused * @param _weiAmount amount of wei sended to the contract * @return calculated amount of tokens * @dev this function calculates tokens by formula wei amount * rate */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @notice This function should be called only when ICO open and only by owner * @dev stops ICO */ function emergencyStop() onlyOwner onlyWhileOpen public { stopped = true; } /** * @notice This function should be called only when ICO open and only by owner * @dev pause ICO */ function pauseICO() onlyOwner whenNotPaused public { paused = true; } /** * @notice This function should be called only by owner * @dev unpause ICO */ function unpauseICO() onlyOwner public { require(paused); paused = false; } /** * @notice This function should be called only by owner * @param _addresses array with addresses * @param _tokenAmounts array with token amounts related to addresses in _addresses array * @dev this function distributes tokens before ICO */ function distributeBeforeICO(address[] _addresses, uint256[] _tokenAmounts) onlyOwner public { require(block.timestamp < startDate); require(_addresses.length > 0); require(_addresses.length == _tokenAmounts.length); for(uint256 i = 0; i < _addresses.length; i++) { daoBase.issueTokens(tokenAddress, _addresses[i], _tokenAmounts[i]); } } /** * @notice This function should be called only by owner and only when ICO finished with success * @param _addresses array with addresses * @param _tokenAmounts array with token amounts related to addresses in _addresses array * @dev this function distributes tokens after ICO */ function distributeAfterICO(address[] _addresses, uint256[] _tokenAmounts) onlyAfterSuccess onlyOwner public { require (_addresses.length > 0); require (_addresses.length == _tokenAmounts.length); for(uint256 i = 0; i < _addresses.length; i++) { daoBase.issueTokens(tokenAddress, _addresses[i], _tokenAmounts[i]); } } /** * @notice This function should be called only by owner and only while ICO is open * @param _member address * @dev this function adds _member to the whitelist */ function addToWhitelist(address _member) onlyOwner onlyWhileOpen public { isWhitelisted[_member] = true; } /** * @param _member address * @return true if _member in whitelist */ function isMemberInWhitelist(address _member) public returns(bool) { return isWhitelisted[_member]; } /** * @notice This function should be called only by owner and only after ICO finished with success * @param _wallet address * @dev forward funds from ICO contract to wallet */ function forwardFunds(address _wallet) onlyAfterSuccess onlyOwner public { _wallet.transfer(address(this).balance); } /** * @notice This function should be called only after ICO fail * @dev returns money for all investors */ function refund() onlyAfterFail public { uint256 payment = deposits[msg.sender]; assert(address(this).balance >= payment); deposits[msg.sender] = 0; msg.sender.transfer(payment); emit Withdrawn(msg.sender, payment); } }
This function should be called only by owner and only after ICO finished with success _wallet address forward funds from ICO contract to wallet/
function forwardFunds(address _wallet) onlyAfterSuccess onlyOwner public { _wallet.transfer(address(this).balance); }
891,830
pragma solidity ^0.4.11; contract BMCPlatform { mapping(bytes32 => address) public proxies; function name(bytes32 _symbol) returns(string); function setProxy(address _address, bytes32 _symbol) returns(uint errorCode); function isOwner(address _owner, bytes32 _symbol) returns(bool); function totalSupply(bytes32 _symbol) returns(uint); function balanceOf(address _holder, bytes32 _symbol) returns(uint); function allowance(address _from, address _spender, bytes32 _symbol) returns(uint); function baseUnit(bytes32 _symbol) returns(uint8); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) returns(uint errorCode); function revokeAsset(bytes32 _symbol, uint _value) returns(uint errorCode); function isReissuable(bytes32 _symbol) returns(bool); function changeOwnership(bytes32 _symbol, address _newOwner) returns(uint errorCode); } contract BMCAsset { function __transferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool); function __approve(address _spender, uint _value, address _sender) returns(bool); function __process(bytes _data, address _sender) payable { throw; } } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function totalSupply() constant returns (uint256 supply); 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); } /** * @title BMC Asset Proxy. * * Proxy implements ERC20 interface and acts as a gateway to a single platform asset. * Proxy adds symbol and caller(sender) when forwarding requests to platform. * Every request that is made by caller first sent to the specific asset implementation * contract, which then calls back to be forwarded onto platform. * * Calls flow: Caller -> * Proxy.func(...) -> * Asset.__func(..., Caller.address) -> * Proxy.__func(..., Caller.address) -> * Platform.proxyFunc(..., symbol, Caller.address) * * Asset implementation contract is mutable, but each user have an option to stick with * old implementation, through explicit decision made in timely manner, if he doesn't agree * with new rules. * Each user have a possibility to upgrade to latest asset contract implementation, without the * possibility to rollback. * * Note: all the non constant functions return false instead of throwing in case if state change * didn't happen yet. */ contract BMCAssetProxy is ERC20 { // Supports BMCPlatform ability to return error codes from methods uint constant OK = 1; // Assigned platform, immutable. BMCPlatform public bmcPlatform; // Assigned symbol, immutable. bytes32 public smbl; // Assigned name, immutable. string public name; string public symbol; /** * Sets platform address, assigns symbol and name. * * Can be set only once. * * @param _bmcPlatform platform contract address. * @param _symbol assigned symbol. * @param _name assigned name. * * @return success. */ function init(BMCPlatform _bmcPlatform, string _symbol, string _name) returns(bool) { if (address(bmcPlatform) != 0x0) { return false; } bmcPlatform = _bmcPlatform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } function stringToBytes32(string memory source) returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /** * Only platform is allowed to call. */ modifier onlyBMCPlatform() { if (msg.sender == address(bmcPlatform)) { _; } } /** * Only current asset owner is allowed to call. */ modifier onlyAssetOwner() { if (bmcPlatform.isOwner(msg.sender, smbl)) { _; } } /** * Returns asset implementation contract for current caller. * * @return asset implementation contract. */ function _getAsset() internal returns(BMCAsset) { return BMCAsset(getVersionFor(msg.sender)); } /** * Returns asset total supply. * * @return asset total supply. */ function totalSupply() constant returns(uint) { return bmcPlatform.totalSupply(smbl); } /** * Returns asset balance for a particular holder. * * @param _owner holder address. * * @return holder balance. */ function balanceOf(address _owner) constant returns(uint) { return bmcPlatform.balanceOf(_owner, smbl); } /** * Returns asset allowance from one holder to another. * * @param _from holder that allowed spending. * @param _spender holder that is allowed to spend. * * @return holder to spender allowance. */ function allowance(address _from, address _spender) constant returns(uint) { return bmcPlatform.allowance(_from, _spender, smbl); } /** * Returns asset decimals. * * @return asset decimals. */ function decimals() constant returns(uint8) { return bmcPlatform.baseUnit(smbl); } /** * Transfers asset balance from the caller to specified receiver. * * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transfer(address _to, uint _value) returns(bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } else { return false; } } /** * Transfers asset balance from the caller to specified receiver adding specified comment. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * * @return success. */ function transferWithReference(address _to, uint _value, string _reference) returns(bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } else { return false; } } /** * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @return success. */ function _transferWithReference(address _to, uint _value, string _reference) internal returns(bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } /** * Performs transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * @param _sender initial caller. * * @return success. */ function __transferWithReference(address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) { return bmcPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /** * Prforms allowance transfer of asset balance between holders. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transferFrom(address _from, address _to, uint _value) returns(bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } else { return false; } } /** * Performs allowance transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * @param _sender initial caller. * * @return success. */ function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) { return bmcPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /** * Sets asset spending allowance for a specified spender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * * @return success. */ function approve(address _spender, uint _value) returns(bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } else { return false; } } /** * Performs allowance setting call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * @param _sender initial caller. * * @return success. */ function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) returns(bool) { return bmcPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /** * Emits ERC20 Transfer event on this contract. * * Can only be, and, called by assigned platform when asset transfer happens. */ function emitTransfer(address _from, address _to, uint _value) onlyBMCPlatform() { Transfer(_from, _to, _value); } /** * Emits ERC20 Approval event on this contract. * * Can only be, and, called by assigned platform when asset allowance set happens. */ function emitApprove(address _from, address _spender, uint _value) onlyBMCPlatform() { Approval(_from, _spender, _value); } /** * Resolves asset implementation contract for the caller and forwards there transaction data, * along with the value. This allows for proxy interface growth. */ function () payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /** * Indicates an upgrade freeze-time start, and the next asset implementation contract. */ event UpgradeProposal(address newVersion); // Current asset implementation contract address. address latestVersion; // Proposed next asset implementation contract address. address pendingVersion; // Upgrade freeze-time start. uint pendingVersionTimestamp; // Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; // Asset implementation contract address that user decided to stick with. // 0x0 means that user uses latest version. mapping(address => address) userOptOutVersion; /** * Only asset implementation contract assigned to sender is allowed to call. */ modifier onlyAccess(address _sender) { if (getVersionFor(_sender) == msg.sender) { _; } } /** * Returns asset implementation contract address assigned to sender. * * @param _sender sender address. * * @return asset implementation contract address. */ function getVersionFor(address _sender) constant returns(address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /** * Returns current asset implementation contract address. * * @return asset implementation contract address. */ function getLatestVersion() constant returns(address) { return latestVersion; } /** * Returns proposed next asset implementation contract address. * * @return asset implementation contract address. */ function getPendingVersion() constant returns(address) { return pendingVersion; } /** * Returns upgrade freeze-time start. * * @return freeze-time start. */ function getPendingVersionTimestamp() constant returns(uint) { return pendingVersionTimestamp; } /** * Propose next asset implementation contract address. * * Can only be called by current asset owner. * * Note: freeze-time should not be applied for the initial setup. * * @param _newVersion asset implementation contract address. * * @return success. */ function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; UpgradeProposal(_newVersion); return true; } /** * Cancel the pending upgrade process. * * Can only be called by current asset owner. * * @return success. */ function purgeUpgrade() onlyAssetOwner() returns(bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Finalize an upgrade process setting new asset implementation contract address. * * Can only be called after an upgrade freeze-time. * * @return success. */ function commitUpgrade() returns(bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Disagree with proposed upgrade, and stick with current asset implementation * until further explicit agreement to upgrade. * * @return success. */ function optOut() returns(bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; return true; } /** * Implicitly agree to upgrade to current and future asset implementation upgrades, * until further explicit disagreement. * * @return success. */ function optIn() returns(bool) { delete userOptOutVersion[msg.sender]; return true; } }
Performs transfer call on the platform by the name of specified sender. Can only be called by asset implementation contract assigned to sender. _to holder address to give to. _value amount to transfer. _reference transfer comment to be included in a platform's Transfer event. _sender initial caller. return success./
function __transferWithReference(address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) { return bmcPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; }
12,958,422
./partial_match/42/0x7729c250167787a6b92df8649065254E1289B1E8/sources/P2PLending.sol
richiedente non deve avere debiti ne richieste di debito attive
function createApplication(uint credit_amount, string memory description) public { require(hasOngoingLoan[msg.sender] == false, 'You have an ongoing Loan'); require(hasOngoingApplication[msg.sender] == false, 'You have an ongoing Application'); require(isBorrower(msg.sender), 'You aren\'t subscribe as a borrower'); applications[msg.sender] = LoanApplication(true, msg.sender, credit_amount, description); hasOngoingApplication[msg.sender] = true; tableProject.push(msg.sender); }
3,374,827
pragma solidity >=0.4.22 <0.6.0; //È necessario acquistare un biglietto inserendo il costo in value e poi cliccando su buyTicket contract Viaggio { string public description = ""; //Stringa per avere un output visivo dei vari comandi uint public check_delay = 0; //Controllo ammontare ritardo address owner; uint check_refund; //Controllo refund richiesto // Tabella in cui viene associato il biglietto con la propria transazione mapping(address=>uint) tickets; //Funzione per comprare il biglietto function buyTicket() public payable { require(msg.value >= 1, "Inserire un value maggiore o uguale ad 1"); description = "Biglietto acquistato"; tickets[msg.sender] = msg.value; owner = msg.sender; } //Funzione che in caso di ritardo rimborsa il cliente function getRefund() public { require(msg.sender == owner); string memory out_msg = ""; uint refund = 0; if (check_delay == 0 && check_refund == 0) { out_msg = "Il treno non ha ritardi, non puoi richiedere alcun rimborso"; } else if (check_delay == 1 && check_refund == 0) { refund = tickets[msg.sender] * 25 / 100; check_refund = 1; check_delay = 0; out_msg = "Il treno ha un ritardo di almeno 15 minuti, riceverai un rimborso del 25%"; } else if (check_delay == 2 && check_refund == 0){ refund = tickets[msg.sender] * 50 / 100; check_refund = 1; check_delay = 0; out_msg = "Il treno ha un ritardo di almeno 30 minuti, riceverai un rimborso del 50%"; } else if (check_delay >= 3 && check_refund == 0){ refund = tickets[msg.sender] * 100 / 100; check_refund = 1; check_delay = 0; out_msg = "Il treno ha un ritardo di almeno 60 minuti, riceverai un rimborso del 100%"; } else if (check_delay == 0 && check_refund == 1){ out_msg = "Hai già ricevuto il rimborso"; } address(msg.sender).transfer(refund); description = out_msg; } //Funzione per aumentare il ritardo del treno in locale function add_delay() public returns(uint) { if (check_refund == 0){ check_delay++; description = "Ritardo treno aumentato"; return check_delay; } else { description = "Error: biglietto rimborsato (?)"; } } }
Funzione per aumentare il ritardo del treno in locale
function add_delay() public returns(uint) { if (check_refund == 0){ check_delay++; description = "Ritardo treno aumentato"; return check_delay; description = "Error: biglietto rimborsato (?)"; } }
13,017,401
./full_match/1/0x48a44ed2062d62B35ecEe53911Fb3bc95E75a1D0/sources/contracts/Router.sol
performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'SSF-V1Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } }
16,393,553
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================ FXS1559_AMO =========================== // ==================================================================== // 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 import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "../Frax/Frax.sol"; import "../ERC20/ERC20.sol"; import "../Frax/Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Governance/AccessControl.sol"; import '../Misc_AMOs/FraxPoolInvestorForV2.sol'; import '../Uniswap/UniswapV2Router02_Modified.sol'; contract FXS1559_AMO is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; FRAXStablecoin private FRAX; FRAXShares private FXS; FraxPoolInvestorForV2 private InvestorAMO; FraxPool private pool; IUniswapV2Router02 private UniRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public collateral_address; address public pool_address; address public owner_address; address public timelock_address; address public custodian_address; address public frax_address; address public fxs_address; address payable public UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public investor_amo_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 public immutable missing_decimals; uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; // Minimum collateral ratio needed for new FRAX minting uint256 public min_cr = 850000; // Amount the contract borrowed uint256 public minted_sum_historical = 0; uint256 public burned_sum_historical = 0; // FRAX -> FXS max slippage uint256 public max_slippage = 200000; // 20% // AMO profits bool public override_amo_profits = false; uint256 public overridden_amo_profit = 0; /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _pool_address, address _collateral_address, address _owner_address, address _custodian_address, address _timelock_address, address _investor_amo_address ) public { frax_address = _frax_contract_address; FRAX = FRAXStablecoin(_frax_contract_address); fxs_address = _fxs_contract_address; FXS = FRAXShares(_fxs_contract_address); pool_address = _pool_address; pool = FraxPool(_pool_address); collateral_address = _collateral_address; collateral_token = ERC20(_collateral_address); investor_amo_address = _investor_amo_address; InvestorAMO = FraxPoolInvestorForV2(_investor_amo_address); timelock_address = _timelock_address; owner_address = _owner_address; custodian_address = _custodian_address; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier onlyCustodian() { require(msg.sender == custodian_address, "You are not the rewards custodian"); _; } /* ========== VIEWS ========== */ function unspentInvestorAMOProfit_E18() public view returns (uint256 unspent_profit_e18) { if (override_amo_profits){ unspent_profit_e18 = overridden_amo_profit; } else { uint256[5] memory allocations = InvestorAMO.showAllocations(); uint256 borrowed_USDC = InvestorAMO.borrowed_balance(); unspent_profit_e18 = allocations[1].add(allocations[2]).add(allocations[3]).sub(borrowed_USDC); unspent_profit_e18 = unspent_profit_e18.mul(10 ** missing_decimals); } } function cr_info() public view returns ( uint256 effective_collateral_ratio, uint256 global_collateral_ratio, uint256 excess_collateral_e18, uint256 frax_mintable ) { global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collat_value = (FRAX.globalCollateralValue()).add(unspentInvestorAMOProfit_E18()); effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 // Same as availableExcessCollatDV() in FraxPool if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (frax_total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) { excess_collateral_e18 = global_collat_value.sub(required_collat_dollar_value_d18); frax_mintable = excess_collateral_e18.mul(COLLATERAL_RATIO_PRECISION).div(global_collateral_ratio); } else { excess_collateral_e18 = 0; frax_mintable = 0; } } /* ========== PUBLIC FUNCTIONS ========== */ // Needed for the Frax contract to not brick when this contract is added as a pool function collatDollarBalance() public view returns (uint256) { return 1e18; // Anti-brick } /* ========== RESTRICTED FUNCTIONS ========== */ // This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from // on the main FRAX contract function _mintFRAXForSwap(uint256 frax_amount) internal { // Make sure the current CR isn't already too low require (FRAX.global_collateral_ratio() > min_cr, "Collateral ratio is already too low"); // Make sure the FRAX minting wouldn't push the CR down too much uint256 current_collateral_E18 = (FRAX.globalCollateralValue()); uint256 cur_frax_supply = FRAX.totalSupply(); uint256 new_frax_supply = cur_frax_supply.add(frax_amount); uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(new_frax_supply); require (new_cr > min_cr, "Minting would cause collateral ratio to be too low"); // Mint the frax FRAX.pool_mint(address(this), frax_amount); } function _swapFRAXforFXS(uint256 frax_amount) internal returns (uint256 frax_spent, uint256 fxs_received) { // Get the FXS price uint256 fxs_price = FRAX.fxs_price(); // Approve the FRAX for the router FRAX.approve(UNISWAP_ROUTER_ADDRESS, frax_amount); address[] memory FRAX_FXS_PATH = new address[](2); FRAX_FXS_PATH[0] = frax_address; FRAX_FXS_PATH[1] = fxs_address; uint256 min_fxs_out = frax_amount.mul(PRICE_PRECISION).div(fxs_price); min_fxs_out = min_fxs_out.sub(min_fxs_out.mul(max_slippage).div(PRICE_PRECISION)); // Buy some FXS with FRAX (uint[] memory amounts) = UniRouterV2.swapExactTokensForTokens( frax_amount, min_fxs_out, FRAX_FXS_PATH, address(this), 2105300114 // A long time from now ); return (amounts[0], amounts[1]); } // Burn unneeded or excess FRAX function mintSwapBurn() public onlyByOwnerOrGovernance { (, , , uint256 mintable_frax) = cr_info(); _mintFRAXForSwap(mintable_frax); (, uint256 fxs_received_ ) = _swapFRAXforFXS(mintable_frax); burnFXS(fxs_received_); } // Burn unneeded or excess FRAX function burnFRAX(uint256 frax_amount) public onlyByOwnerOrGovernance { FRAX.burn(frax_amount); burned_sum_historical = burned_sum_historical.add(frax_amount); } // Burn unneeded FXS function burnFXS(uint256 amount) public onlyByOwnerOrGovernance { FXS.approve(address(this), amount); FXS.pool_burn_from(address(this), amount); } /* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */ function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setPool(address _pool_address) external onlyByOwnerOrGovernance { pool_address = _pool_address; pool = FraxPool(_pool_address); } function setMinimumCollateralRatio(uint256 _min_cr) external onlyByOwnerOrGovernance { min_cr = _min_cr; } function setMaxSlippage(uint256 _max_slippage) external onlyByOwnerOrGovernance { max_slippage = _max_slippage; } function setAMOProfits(uint256 _overridden_amo_profit_e18, bool _override_amo_profits) external onlyByOwnerOrGovernance { overridden_amo_profit = _overridden_amo_profit_e18; // E18 override_amo_profits = _override_amo_profits; } function setRouter(address payable _router_address) external onlyByOwnerOrGovernance { UNISWAP_ROUTER_ADDRESS = _router_address; UniRouterV2 = IUniswapV2Router02(_router_address); } function setInvestorAMO(address _investor_amo_address) external onlyByOwnerOrGovernance { investor_amo_address = _investor_amo_address; InvestorAMO = FraxPoolInvestorForV2(_investor_amo_address); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard ERC20(tokenAddress).transfer(custodian_address, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= FRAXShares (FXS) ========================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/IERC20.sol"; import "../Frax/Frax.sol"; import "../Math/SafeMath.sol"; import "../Governance/AccessControl.sol"; contract FRAXShares is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ string public symbol; string public name; uint8 public constant decimals = 18; address public FRAXStablecoinAdd; uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups address public owner_address; address public oracle_address; address public timelock_address; // Governance timelock address FRAXStablecoin private FRAX; bool public trackingVotes = true; // Tracking votes (only change if need to disable votes) // A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /* ========== MODIFIERS ========== */ modifier onlyPools() { require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _oracle_address, address _owner_address, address _timelock_address ) public { name = _name; symbol = _symbol; owner_address = _owner_address; oracle_address = _oracle_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _mint(owner_address, genesis_supply); // Do a checkpoint for the owner _writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply)); } /* ========== RESTRICTED FUNCTIONS ========== */ function setOracle(address new_oracle) external onlyByOwnerOrGovernance { oracle_address = new_oracle; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance { FRAX = FRAXStablecoin(frax_contract_address); } function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance { FXS_DAO_min = min_FXS; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function mint(address to, uint256 amount) public onlyPools { _mint(to, amount); } // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) function pool_mint(address m_address, uint256 m_amount) external onlyPools { if(trackingVotes){ uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes trackVotes(address(this), m_address, uint96(m_amount)); } super._mint(m_address, m_amount); emit FXSMinted(address(this), m_address, m_amount); } // This function is what other frax pools will call to burn FXS function pool_burn_from(address b_address, uint256 b_amount) external onlyPools { if(trackingVotes){ trackVotes(b_address, address(this), uint96(b_amount)); uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes } super._burnFrom(b_address, b_amount); emit FXSBurned(b_address, address(this), b_amount); } function toggleVotes() external onlyByOwnerOrGovernance { trackingVotes = !trackingVotes; } /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(_msgSender(), recipient, uint96(amount)); } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(sender, recipient, uint96(amount)); } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /* ========== PUBLIC FUNCTIONS ========== */ /** * @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 (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "FXS::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; } /* ========== INTERNAL FUNCTIONS ========== */ // From compound's _moveDelegates // Keep track of votes. "Delegates" is a misnomer here function trackVotes(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, "FXS::_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, "FXS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[voter] = nCheckpoints + 1; } emit VoterVotesChanged(voter, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint 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 (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /* ========== EVENTS ========== */ /// @notice An event thats emitted when a voters account's vote balance changes event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance); // Track FXS burned event FXSBurned(address indexed from, address indexed to, uint256 amount); // Track FXS minted event FXSMinted(address indexed from, address indexed to, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FRAXStablecoin (FRAX) ====================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } ChainlinkETHUSDPriceConsumer private eth_usd_pricer; uint8 private eth_usd_pricer_decimals; UniswapPairOracle private fraxEthOracle; UniswapPairOracle private fxsEthOracle; string public symbol; string public name; uint8 public constant decimals = 18; address public owner_address; address public creator_address; address public timelock_address; // Governance timelock address address public controller_address; // Controller contract to dynamically adjust system parameters automatically address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] public frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio() uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1 uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can call this function"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == owner_address || msg.sender == timelock_address || frax_pools[msg.sender] == true, "You are not the owner, the governance timelock, or a pool"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _creator_address, address _timelock_address ) public { name = _name; symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); owner_address = _creator_address; _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); frax_step = 2500; // 6 decimals of precision, equal to 0.25% global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision) refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } function eth_usd_price() public view returns (uint256) { return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee, // redemption_fee() uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 public last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); uint256 frax_price_cur = frax_price(); require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh"); // Step increments are 0.25% (upon genesis, changable by setFraxStep()) if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0 global_collateral_ratio = 0; } else { global_collateral_ratio = global_collateral_ratio.sub(frax_step); } } else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio if(global_collateral_ratio.add(frax_step) >= 1000000){ global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000 } else { global_collateral_ratio = global_collateral_ratio.add(frax_step); } } last_call_time = block.timestamp; // Set the time of the last expansion } /* ========== RESTRICTED FUNCTIONS ========== */ // Used by pools when user redeems function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit FRAXMinted(msg.sender, m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerOrGovernance { require(frax_pools[pool_address] == false, "address already exists"); frax_pools[pool_address] = true; frax_pools_array.push(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerOrGovernance { require(frax_pools[pool_address] == true, "address doesn't exist already"); // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance { redemption_fee = red_fee; } function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance { minting_fee = min_fee; } function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance { frax_step = _new_step; } function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance { price_target = _new_price_target; } function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance { refresh_cooldown = _new_cooldown; } function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance { fxs_address = _fxs_address; } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance { eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setController(address _controller_address) external onlyByOwnerOrGovernance { controller_address = _controller_address; } function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance { price_band = _price_band; } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { frax_eth_oracle_address = _frax_oracle_addr; fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); weth_address = _weth_address; } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { fxs_eth_oracle_address = _fxs_oracle_addr; fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr); weth_address = _weth_address; } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; } /* ========== EVENTS ========== */ // Track FRAX burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); // Track FRAX minted event FRAXMinted(address indexed from, address indexed to, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/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 {ERC20Mintable}. * * 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.approve(address spender, uint256 amount) */ 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 the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================= FraxPool ============================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../../Math/SafeMath.sol"; import "../../FXS/FXS.sol"; import "../../Frax/Frax.sol"; import "../../ERC20/ERC20.sol"; import "../../Oracle/UniswapPairOracle.sol"; import "../../Governance/AccessControl.sol"; import "./FraxPoolLibrary.sol"; contract FraxPool is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; address private collateral_address; address private owner_address; address private frax_contract_address; address private fxs_contract_address; address private timelock_address; FRAXShares private FXS; FRAXStablecoin private FRAX; UniswapPairOracle private collatEthOracle; address public collat_eth_oracle_address; address private weth_address; uint256 public minting_fee; uint256 public redemption_fee; uint256 public buyback_fee; uint256 public recollat_fee; mapping (address => uint256) public redeemFXSBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolFXS; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 private immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 0; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate = 7500; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl Roles bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _collateral_address, address _creator_address, address _timelock_address, uint256 _pool_ceiling ) public { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); frax_contract_address = _frax_contract_address; fxs_contract_address = _fxs_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; owner_address = _creator_address; collateral_token = ERC20(_collateral_address); pool_ceiling = _pool_ceiling; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this Frax pool function collatDollarBalance() public view returns (uint256) { if(collateralPricePaused == true){ return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Returns the price of the pool collateral in USD function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { uint256 eth_usd_price = FRAX.eth_usd_price(); return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals))); } } function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance { collat_eth_oracle_address = _collateral_weth_oracle_address; collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused { uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX( getCollateralPrice(), collateral_amount_d18 ); //1 FRAX for each $1 worth of collateral frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, frax_amount_d18); } // 0% collateral-backed function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX( fxs_price, // X FXS / 1 USD fxs_amount_d18 ); frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); FXS.pool_burn_from(msg.sender, fxs_amount_d18); FRAX.pool_mint(msg.sender, frax_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params( fxs_price, getCollateralPrice(), fxs_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params); mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= mint_amount, "Slippage limit reached"); require(fxs_needed <= fxs_amount, "Not enough FXS inputted"); FXS.pool_burn_from(msg.sender, fxs_needed); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX( getCollateralPrice(), FRAX_amount_precision ); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6); require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); } // Will fail if fully collateralized or algorithmic // Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); uint256 col_price_usd = getCollateralPrice(); uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals); uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd); require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // Redeem FRAX for FXS. 0% collateral-backed function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio == 0, "Collateral ratio must be 0"); uint256 fxs_dollar_value_d18 = FRAX_amount; fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; require(FXS_out_min <= fxs_amount, "Slippage limit reached"); // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendFXS = false; bool sendCollateral = false; uint FXSAmount; uint CollateralAmount; // Use Checks-Effects-Interactions pattern if(redeemFXSBalances[msg.sender] > 0){ FXSAmount = redeemFXSBalances[msg.sender]; redeemFXSBalances[msg.sender] = 0; unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount); sendFXS = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendFXS == true){ FXS.transfer(msg.sender, FXSAmount); } if(sendCollateral == true){ collateral_token.transfer(msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); } // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external { require(buyBackPaused == false, "Buyback is paused"); uint256 fxs_price = FRAX.fxs_price(); FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params( availableExcessCollatDV(), fxs_price, getCollateralPrice(), FXS_amount ); (uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Give the sender their desired collateral and burn the FXS FXS.pool_burn_from(msg.sender, FXS_amount); collateral_token.transfer(msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } /* ========== EVENTS ========== */ } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../Uniswap/Interfaces/IUniswapV2Factory.sol'; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; import '../Uniswap/UniswapV2OracleLibrary.sol'; import '../Uniswap/UniswapV2Library.sol'; // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapPairOracle { using FixedPoint for *; address owner_address; address timelock_address; uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price) uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair owner_address = _owner_address; timelock_address = _timelock_address; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnerOrGovernance { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance { ALLOW_STALE_CONSULTS = _allow_stale_consults; } // Check if update() can be called instead of wasting gas calling it function canUpdate() public view returns (bool) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired return (timeElapsed >= PERIOD); } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED'); // Overflow is desired, casting never truncates // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that the price is not stale require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE'); if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'UniswapPairOracle: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../Utils/EnumerableSet.sol"; import "../Utils/Address.sol"; import "../Common/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FraxPoolInvestorForV2 ====================== // ==================================================================== // 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 import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "../Frax/Frax.sol"; import "../ERC20/ERC20.sol"; import "../ERC20/Variants/Comp.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Governance/AccessControl.sol"; import "../Frax/Pools/FraxPool.sol"; import "./yearn/IyUSDC_V2_Partial.sol"; import "./aave/IAAVELendingPool_Partial.sol"; import "./aave/IAAVE_aUSDC_Partial.sol"; import "./compound/ICompComptrollerPartial.sol"; import "./compound/IcUSDC_Partial.sol"; // Lower APY: yearn, AAVE, Compound // Higher APY: KeeperDAO, BZX, Harvest contract FraxPoolInvestorForV2 is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; FRAXShares private FXS; FRAXStablecoin private FRAX; FraxPool private pool; // Pools and vaults IyUSDC_V2_Partial private yUSDC_V2 = IyUSDC_V2_Partial(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9); IAAVELendingPool_Partial private aaveUSDC_Pool = IAAVELendingPool_Partial(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); IAAVE_aUSDC_Partial private aaveUSDC_Token = IAAVE_aUSDC_Partial(0xBcca60bB61934080951369a648Fb03DF4F96263C); IcUSDC_Partial private cUSDC = IcUSDC_Partial(0x39AA39c021dfbaE8faC545936693aC917d5E7563); // Reward Tokens Comp private COMP = Comp(0xc00e94Cb662C3520282E6f5717214004A7f26888); ICompComptrollerPartial private CompController = ICompComptrollerPartial(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public collateral_address; address public pool_address; address public owner_address; address public timelock_address; address public custodian_address; address public weth_address = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 public immutable missing_decimals; uint256 private constant PRICE_PRECISION = 1e6; // Max amount of collateral this contract can borrow from the FraxPool uint256 public borrow_cap = uint256(20000e6); // Amount the contract borrowed uint256 public borrowed_balance = 0; uint256 public borrowed_historical = 0; uint256 public paid_back_historical = 0; // Allowed strategies (can eventually be made into an array) bool public allow_yearn = true; bool public allow_aave = true; bool public allow_compound = true; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier onlyCustodian() { require(msg.sender == custodian_address, "You are not the rewards custodian"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _pool_address, address _collateral_address, address _owner_address, address _custodian_address, address _timelock_address ) public { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); pool_address = _pool_address; pool = FraxPool(_pool_address); collateral_address = _collateral_address; collateral_token = ERC20(_collateral_address); timelock_address = _timelock_address; owner_address = _owner_address; custodian_address = _custodian_address; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /* ========== VIEWS ========== */ function showAllocations() external view returns (uint256[5] memory allocations) { // IMPORTANT // Should ONLY be used externally, because it may fail if any one of the functions below fail // All numbers given are assuming xyzUSDC, etc. is converted back to actual USDC allocations[0] = collateral_token.balanceOf(address(this)); // Unallocated allocations[1] = (yUSDC_V2.balanceOf(address(this))).mul(yUSDC_V2.pricePerShare()).div(1e6); // yearn allocations[2] = aaveUSDC_Token.balanceOf(address(this)); // AAVE allocations[3] = (cUSDC.balanceOf(address(this)).mul(cUSDC.exchangeRateStored()).div(1e18)); // Compound. Note that cUSDC is E8 uint256 sum_tally = 0; for (uint i = 1; i < 5; i++){ if (allocations[i] > 0){ sum_tally = sum_tally.add(allocations[i]); } } allocations[4] = sum_tally; // Total Staked } function showRewards() external view returns (uint256[1] memory rewards) { // IMPORTANT // Should ONLY be used externally, because it may fail if COMP.balanceOf() fails rewards[0] = COMP.balanceOf(address(this)); // COMP } /* ========== PUBLIC FUNCTIONS ========== */ // Needed for the Frax contract to function function collatDollarBalance() external view returns (uint256) { // Needs to mimic the FraxPool value and return in E18 // Only thing different should be borrowed_balance vs balanceOf() if(pool.collateralPricePaused() == true){ return borrowed_balance.mul(10 ** missing_decimals).mul(pool.pausedPrice()).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = UniswapPairOracle(pool.collat_eth_oracle_address()).consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return borrowed_balance.mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // This is basically a workaround to transfer USDC from the FraxPool to this investor contract // This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from // on the main FRAX contract // It mints FRAX from nothing, and redeems it on the target pool for collateral and FXS // The burn can be called separately later on function mintRedeemPart1(uint256 frax_amount) public onlyByOwnerOrGovernance { require(allow_yearn || allow_aave || allow_compound, 'All strategies are currently off'); uint256 redemption_fee = pool.redemption_fee(); uint256 col_price_usd = pool.getCollateralPrice(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 redeem_amount_E6 = (frax_amount.mul(uint256(1e6).sub(redemption_fee))).div(1e6).div(10 ** missing_decimals); uint256 expected_collat_amount = redeem_amount_E6.mul(global_collateral_ratio).div(1e6); expected_collat_amount = expected_collat_amount.mul(1e6).div(col_price_usd); require(borrowed_balance.add(expected_collat_amount) <= borrow_cap, "Borrow cap reached"); borrowed_balance = borrowed_balance.add(expected_collat_amount); borrowed_historical = borrowed_historical.add(expected_collat_amount); // Mint the frax FRAX.pool_mint(address(this), frax_amount); // Redeem the frax FRAX.approve(address(pool), frax_amount); pool.redeemFractionalFRAX(frax_amount, 0, 0); } function mintRedeemPart2() public onlyByOwnerOrGovernance { pool.collectRedemption(); } function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance { // Still paying back principal if (amount <= borrowed_balance) { borrowed_balance = borrowed_balance.sub(amount); } // Pure profits else { borrowed_balance = 0; } paid_back_historical = paid_back_historical.add(amount); collateral_token.transfer(address(pool), amount); } function burnFXS(uint256 amount) public onlyByOwnerOrGovernance { FXS.approve(address(this), amount); FXS.pool_burn_from(address(this), amount); } /* ========== yearn V2 ========== */ function yDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_yearn, 'yearn strategy is currently off'); collateral_token.approve(address(yUSDC_V2), USDC_amount); yUSDC_V2.deposit(USDC_amount); } // E6 function yWithdrawUSDC(uint256 yUSDC_amount) public onlyByOwnerOrGovernance { yUSDC_V2.withdraw(yUSDC_amount); } /* ========== AAVE V2 ========== */ function aaveDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_aave, 'AAVE strategy is currently off'); collateral_token.approve(address(aaveUSDC_Pool), USDC_amount); aaveUSDC_Pool.deposit(collateral_address, USDC_amount, address(this), 0); } // E6 function aaveWithdrawUSDC(uint256 aUSDC_amount) public onlyByOwnerOrGovernance { aaveUSDC_Pool.withdraw(collateral_address, aUSDC_amount, address(this)); } /* ========== Compound cUSDC + COMP ========== */ function compoundMint_cUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_compound, 'Compound strategy is currently off'); collateral_token.approve(address(cUSDC), USDC_amount); cUSDC.mint(USDC_amount); } // E8 function compoundRedeem_cUSDC(uint256 cUSDC_amount) public onlyByOwnerOrGovernance { // NOTE that cUSDC is E8, NOT E6 cUSDC.redeem(cUSDC_amount); } function compoundCollectCOMP() public onlyByOwnerOrGovernance { address[] memory cTokens = new address[](1); cTokens[0] = address(cUSDC); CompController.claimComp(address(this), cTokens); // CompController.claimComp(address(this), ); } /* ========== Custodian ========== */ function withdrawRewards() public onlyCustodian { COMP.transfer(custodian_address, COMP.balanceOf(address(this))); } /* ========== RESTRICTED FUNCTIONS ========== */ function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setWethAddress(address _weth_address) external onlyByOwnerOrGovernance { weth_address = _weth_address; } function setMiscRewardsCustodian(address _custodian_address) external onlyByOwnerOrGovernance { custodian_address = _custodian_address; } function setPool(address _pool_address) external onlyByOwnerOrGovernance { pool_address = _pool_address; pool = FraxPool(_pool_address); } function setBorrowCap(uint256 _borrow_cap) external onlyByOwnerOrGovernance { borrow_cap = _borrow_cap; } function setAllowedStrategies(bool _yearn, bool _aave, bool _compound) external onlyByOwnerOrGovernance { allow_yearn = _yearn; allow_aave = _aave; allow_compound = _compound; } function emergencyRecoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard ERC20(tokenAddress).transfer(custodian_address, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Interfaces/IUniswapV2Factory.sol'; import './TransferHelper.sol'; import './Interfaces/IUniswapV2Router02.sol'; import './UniswapV2Library.sol'; import '../Math/SafeMath.sol'; import '../ERC20/IERC20.sol'; import '../ERC20/IWETH.sol'; contract UniswapV2Router02_Modified is IUniswapV2Router02 { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IUniswapV2Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = UniswapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); TransferHelper.safeTransferFrom(WETH, msg.sender, pair, amountETH); // IWETH(WETH).transferFrom(msg.sender, pair, amountETH); // IWETH(WETH).deposit{value: amountETH}(); // assert(IWETH(WETH).transfer(pair, amountETH)); // require(false, "HELLO: HOW ARE YOU TODAY!"); liquidity = IUniswapV2Pair(pair).mint(to); // << PROBLEM IS HERE // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { // for (uint i; i < path.length - 1; i++) { // (address input, address output) = (path[i], path[i + 1]); // (address token0,) = UniswapV2Library.sortTokens(input, output); // IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)); // uint amountInput; // uint amountOutput; // { // scope to avoid stack too deep errors // (uint reserve0, uint reserve1,) = pair.getReserves(); // (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); // amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); // amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput); // } // (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); // address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; // pair.swap(amount0Out, amount1Out, to, new bytes(0)); // } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { // TransferHelper.safeTransferFrom( // path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn // ); // uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); // _swapSupportingFeeOnTransferTokens(path, to); // require( // IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, // 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' // ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { // require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); // uint amountIn = msg.value; // IWETH(WETH).deposit{value: amountIn}(); // assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn)); // uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); // _swapSupportingFeeOnTransferTokens(path, to); // require( // IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, // 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' // ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { // require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); // TransferHelper.safeTransferFrom( // path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn // ); // _swapSupportingFeeOnTransferTokens(path, address(this)); // uint amountOut = IERC20(WETH).balanceOf(address(this)); // require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); // IWETH(WETH).withdraw(amountOut); // TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return UniswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsIn(factory, amountOut, path); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /* * @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: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; // Due to compiling issues, _name, _symbol, and _decimals were removed /** * @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 {ERC20Mintable}. * * 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 ERC20Custom is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; /** * @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.approve(address spender, uint256 amount) */ 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 the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "../Math/SafeMath.sol"; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @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); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "./AggregatorV3Interface.sol"; contract ChainlinkETHUSDPriceConsumer { AggregatorV3Interface internal priceFeed; constructor() public { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } function getDecimals() public view returns (uint8) { return priceFeed.decimals(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../Math/SafeMath.sol"; library FraxPoolLibrary { using SafeMath for uint256; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFF_Params { uint256 fxs_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackFXS_Params { uint256 excess_collateral_dollar_value_d18; uint256 fxs_price_usd; uint256 col_price_usd; uint256 FXS_amount; } // ================ Functions ================ function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) { return fxs_amount_d18.mul(fxs_price_usd).div(1e6); } // Must be internal because of the struct function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount uint256 fxs_dollar_value_d18; uint256 c_dollar_value_d18; // Scoping for stack concerns { // USD amounts of the collateral and the FXS fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6); c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6); } uint calculated_fxs_dollar_value_d18 = (c_dollar_value_d18.mul(1e6).div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd); return ( c_dollar_value_d18.add(calculated_fxs_dollar_value_d18), calculated_fxs_needed ); } function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) { return FRAX_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6); require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of FXS provided uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeFRAXInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Babylonian.sol'; // 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)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; // 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) { 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 (uint112 reserve0, uint112 reserve1, uint32 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; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Interfaces/IUniswapV2Pair.sol'; import './Interfaces/IUniswapV2Factory.sol'; import "../Math/SafeMath.sol"; 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'); } // Less efficient than the CREATE2 method below function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairForCreate2(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 )))); // this matches the CREATE2 in UniswapV2Factory.createPair } // 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; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; // 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 } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2020-03-04 */ pragma solidity 0.6.11; pragma experimental ABIEncoderV2; contract Comp { /// @notice EIP-20 token name for this token string public constant name = "Compound"; /// @notice EIP-20 token symbol for this token string public constant symbol = "COMP"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 10000000e18; // 10 million Comp /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 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 The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { 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) 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), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::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 (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::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]; 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), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_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, "Comp::_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, "Comp::_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, "Comp::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint 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 (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../../ERC20/IERC20.sol'; // https://etherscan.io/address/0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9 // Some functions were omitted for brevity. See the contract for details interface IyUSDC_V2_Partial is IERC20 { function balance() external returns (uint); function available() external returns (uint); function earn() external; function deposit(uint _amount) external; function withdraw(uint _shares) external; function pricePerShare() external view returns (uint); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import '../../ERC20/IERC20.sol'; // Original at https://etherscan.io/address/0xc6845a5c768bf8d7681249f8927877efda425baf#code // Address [0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9] used is a proxy // Some functions were omitted for brevity. See the contract for details interface IAAVELendingPool_Partial is IERC20 { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import '../../ERC20/IERC20.sol'; // Original at https://etherscan.io/address/0xbCe3076b0d8EB2f640D4089A4929fE8c1a438213#code // Address [0xBcca60bB61934080951369a648Fb03DF4F96263C] used is a proxy // Some functions were omitted for brevity. See the contract for details interface IAAVE_aUSDC_Partial is IERC20 { } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // Original at https://etherscan.io/address/0xbe7616B06f71e363A310Aa8CE8aD99654401ead7#code // Address [0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B] used is a proxy // Some functions were omitted for brevity. See the contract for details interface ICompComptrollerPartial { function claimComp(address holder) external; function claimComp(address holder, address[] memory cTokens) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import '../../ERC20/IERC20.sol'; // Original at https://etherscan.io/address/0x39aa39c021dfbae8fac545936693ac917d5e7563#code // Some functions were omitted for brevity. See the contract for details // https://compound.finance/docs/ctokens interface IcUSDC_Partial is IERC20 { function mint(uint mintAmount) external returns (uint); // redeemAmount = # of cUSDC function redeem(uint redeemAmount) external returns (uint); // redeemAmount = # of USDC function redeemUnderlying(uint redeemAmount) external returns (uint); // Multiply this by the E8 balance of cUSDC, then divide the product by E16 function exchangeRateStored() external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; // 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'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function transferFrom(address src, address dst, uint wad) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
This is needed to avoid costly repeat calls to different getter functions It is cheaper gas-wise to just dump everything and only use some of the info
function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( ); }
221,029
/* Copyright 2021 Project Galaxy. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; //import "SafeMath.sol"; //import "Address.sol"; import "ERC1155.sol"; import "Ownable.sol"; import "IStarNFT.sol"; /** * based on https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol */ contract StarNFTV1 is ERC1155, IStarNFT, Ownable { using SafeMath for uint256; // using Address for address; // using ERC165Checker for address; /* ============ Events ============ */ event EventMinterAdded(address indexed newMinter); event EventMinterRemoved(address indexed oldMinter); /* ============ Modifiers ============ */ /** * Only minter. */ modifier onlyMinter() { require(minters[msg.sender], "must be minter"); _; } /* ============ Enums ================ */ /* ============ Structs ============ */ /* ============ State Variables ============ */ // Used as the URI for all token types by ID substitution, e.g. https://galaxy.eco/{address}/{id}.json string public baseURI; // Mint and burn star. mapping(address => bool) public minters; // Total star count, including burnt nft uint256 public starCount; /* ============ Constructor ============ */ constructor () ERC1155("") {} /* ============ External Functions ============ */ function mint(address account, uint256 powah) external onlyMinter override returns (uint256) { starCount++; uint256 sID = starCount; _mint(account, sID, 1, ""); return sID; } function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external onlyMinter override returns (uint256[] memory) { uint256[] memory ids = new uint256[](amount); uint256[] memory amounts = new uint256[](amount); for (uint i = 0; i < ids.length; i++) { starCount++; ids[i] = starCount; amounts[i] = 1; } _mintBatch(account, ids, amounts, ""); return ids; } function burn(address account, uint256 id) external onlyMinter override { require(isApprovedForAll(account, _msgSender()), "ERC1155: caller is not approved"); _burn(account, id, 1); } function burnBatch(address account, uint256[] calldata ids) external onlyMinter override { require(isApprovedForAll(account, _msgSender()), "ERC1155: caller is not approved"); uint256[] memory amounts = new uint256[](ids.length); for (uint i = 0; i < ids.length; i++) { amounts[i] = 1; } _burnBatch(account, ids, amounts); } /** * PRIVILEGED MODULE FUNCTION. Sets a new baseURI for all token types. */ function setURI(string memory newURI) external onlyOwner { baseURI = newURI; } /** * PRIVILEGED MODULE FUNCTION. Add a new minter. */ function addMinter(address minter) external onlyOwner { require(minter != address(0), "Minter must not be null address"); require(!minters[minter], "Minter already added"); minters[minter] = true; emit EventMinterAdded(minter); } /** * PRIVILEGED MODULE FUNCTION. Remove a old minter. */ function removeMinter(address minter) external onlyOwner { require(minters[minter], "Minter does not exist"); delete minters[minter]; emit EventMinterRemoved(minter); } /* ============ External Getter Functions ============ */ /** * 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 id) external view override returns (string memory) { require(id <= starCount, "NFT does not exist"); // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(baseURI).length == 0) { return ""; } else { // bytes memory b = new bytes(32); // assembly { mstore(add(b, 32), id) } // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(baseURI, uint2str(id), ".json")); } } /** * Is the nft owner. * Requirements: * - `account` must not be zero address. */ function isOwnerOf(address account, uint256 id) public view override returns (bool) { return balanceOf(account, id) == 1; } function getNumMinted() external view override returns (uint256) { return starCount; } /* ============ Internal Functions ============ */ /* ============ Private Functions ============ */ /* ============ Util Functions ============ */ function uint2str(uint _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bStr = new bytes(len); uint k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bStr[k] = b1; _i /= 10; } return string(bStr); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "IERC1155.sol"; import "IERC1155MetadataURI.sol"; import "IERC1155Receiver.sol"; import "Context.sol"; import "ERC165.sol"; import "SafeMath.sol"; import "Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * 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}. */ constructor (string memory uri_) public { _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 IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(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 IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. 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.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 "IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /* Copyright 2021 Project Galaxy. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title IStarNFT * @author Galaxy Protocol * * Interface for operating with StarNFTs. */ interface IStarNFT { /* ============ Events =============== */ /* ============ Functions ============ */ function isOwnerOf(address, uint256) external view returns (bool); function getNumMinted() external view returns (uint256); // mint function mint(address account, uint256 powah) external returns (uint256); function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external returns (uint256[] memory); function burn(address account, uint256 id) external; function burnBatch(address account, uint256[] calldata ids) external; }
Is the nft owner. Requirements: - `account` must not be zero address./
function isOwnerOf(address account, uint256 id) public view override returns (bool) { return balanceOf(account, id) == 1; }
589,542
pragma solidity >=0.5.0 <0.6.0; import "./installed_contracts/zeppelin/contracts/math/SafeMath.sol"; import "./installed_contracts/zeppelin/contracts/math/SafeMath16.sol"; import "./installed_contracts/zeppelin/contracts/ownership/Ownable.sol"; /** * @title Certification Smart Contract * @author Harsh Rajat | https://github.com/HarshRajat/ * @notice Create Certification Smart Contract to administer, award and manage pupils certifications * @dev This Contract handles management of pupils certications */ contract Certification is Ownable { // Using SafeMath Library using SafeMath for uint; using SafeMath16 for uint16; /* *************** * DEFINE ENUMS *************** */ enum grades { Good, Great, Outstanding, Epic, Legendary } // for grades enum assignmentStatus { Inactive, Pending, Completed, Cancelled } // for assignment information /* *************** * DEFINE CONSTANTS *************** */ /* *************** * DEFINE STRUCTURES *************** */ /* Admin Struct handles the admin mapping of address as well as the id to which they are assigned to. */ struct Admin { bool authorized; uint id; } /* Assignment Struct handles the assignments given to the studens. the assignmentInfo enum is used to find out if the assignment is active or not and the associated status. Since all assignment will have their status as Inactive at first, it can also be used to determine the status of final project. The mapping 0 of Assignment Struct for these reasons is reserved as index 0. */ struct Assignment { string link; //the github link of the assignment assignmentStatus status; // for the assignment information } /* Certification of Students can be handled in a struct, proposed solution: We use mapping of uint to store id which is mapped to individual students, a reverse function to map that id to student email id is also used to retrieve the student using their email id. - firstName - using bytes32 to save space, handles 32 characters - lastName - using bytes32 to save space, handles 32 characters - commendation - using bytes32 to save space, handles 32 characters - grade - using grades enum since grade is from 1 to 5, max range 256 - assignmentIndex - using uint16 to handle it, max range 65536 | IMP: 0 is always reserved for Final Project - active - determines if the student has been deemed active or inactive by the admins - email - is used to reverse map for a student and to display email as well - assigments - is a mapping of uint16 to struct Assignment */ struct Student { bytes32 firstName; bytes32 lastName; bytes32 commendation; grades grade; uint16 assignmentIndex; bool active; string email; mapping (uint16 => Assignment) assignments; } /* *************** * DEFINE VARIABLES *************** */ mapping (address => Admin) public admins; mapping (uint => address) public adminsReverseMapping; uint public adminIndex; uint public maxAdmins; // for setting the max admin limit mapping (uint => Student) public students; mapping (string => uint) public studentsReverseMapping; uint public studentIndex; /* *************** * DEFINE EVENTS *************** */ // Admins Related event AdminAdded(address adminAddr, uint adminIndex); // Admin Added event AdminRemoved(address adminAddr, uint adminIndex); // Admin Removed event AdminLimitChanged(uint newLimit); // Max Admin Limit Changed // Students Related event StudentAdded(string email, bytes32 firstName, bytes32 lastName, bytes32 commendation, grades grade); event StudentRemoved(string email); event StudentNameUpdated(string email, bytes32 firstName, bytes32 lastName); event StudentCommendationUpdated(string email, bytes32 commendation); event StudentGradeUpdated(string email, grades grade); event StudentEmailUpdated(string oldEmail, string newEmail); // Assignments Related event AssignmentAdded(string indexed email, string link, assignmentStatus status, uint16 index); event AssignmentUpdated(string indexed email, uint16 index, assignmentStatus status); /* *************** * DEFINE MODIFIERS *************** */ // The modifier restricts function access to only admins or owners modifier onlyAdmins() { require( admins[msg.sender].authorized, "Only Admins allowed" ); _; } // The modifier restricts function access to only non-owner admins modifier onlyNonOwnerAdmins(address _addr) { require( admins[_addr].authorized && owner() != _addr, "Only Non-Owner Admin allower" ); _; } // The modifier checks the limit of number of Admins allowed modifier onlyPermissibleAdminLimit() { require( adminIndex < maxAdmins, "Admins Limit Exceeded" ); _; } // The modifier checks for non-existent students modifier onlyNonExistentStudents(string memory _email) { require( !students[studentsReverseMapping[_email]].active, "Student already Exists" ); _; } // The modifier checks for valid students modifier onlyValidStudents(string memory _email) { require( students[studentsReverseMapping[_email]].active, "Student doesn't Exists" ); _; } /* *************** * DEFINE FUNCTIONS *************** */ constructor () public { maxAdmins = 2; // mapping the max number of admins including the owner // Add Owner as admin _addAdmin(msg.sender); } // 1. OVERRIDE OWANABLE FUNCTIONS FOR ADMIN FUNCTIONALITY // Remove Previous Admin and Add New Owner if necessary | Overriding Ownable.sol function transferOwnership(address newOwner) public onlyOwner { // Remove Admin _removeAdmin(owner()); // Add New Admin _addAdmin(newOwner); // Call parent super._transferOwnership(newOwner); } // Remove Owner from Admin as well | Overriding Ownable.sol function renounceOwnership() public onlyOwner { // Remove Admin _removeAdmin(owner()); // Call parent super.renounceOwnership(); } // 2. ADMIN RELATED FUNCTIONS // To Add Administrator function addAdmin(address _addr) onlyOwner onlyPermissibleAdminLimit public { // call helper function since constructor needs this _addAdmin(_addr); } // Private helper function to add administrator function _addAdmin(address _addr) private { // If Admin doesn't exist alread then add if (!admins[_addr].authorized) { // Add to admins admins[_addr] = Admin( true, // authorized value adminIndex // admin count ); // Add to admins info for reverse mapping adminsReverseMapping[adminIndex] = _addr; // Increase admin index adminIndex = adminIndex.add(1); // Emit event emit AdminAdded(_addr, adminIndex); } } // To Remove Administrator, can't remove an owner address function removeAdmin(address _addr) onlyOwner onlyNonOwnerAdmins(_addr) external { _removeAdmin(_addr); } // Private helper function to remove administrator function _removeAdmin(address _addr) private { // check if the admin index is greater than 0 require( adminIndex > 0, "Requires atleast 1 Admin" ); // a bit tricky, swap and delete to maintain mapping if (admins[_addr].authorized) { // get id of the admin to be deleted uint swappableId = admins[_addr].id; // swap the admins info and update admins mapping // get the last adminsReverseMapping address for swapping address swappableAddress = adminsReverseMapping[adminIndex]; // swap the adminsReverseMapping and then reduce admin index adminsReverseMapping[swappableId] = adminsReverseMapping[adminIndex]; // also remap the admins id admins[swappableAddress].id = swappableId; // delete and reduce admin index delete(admins[_addr]); delete(adminsReverseMapping[adminIndex]); adminIndex = adminIndex.sub(1); // Emit event emit AdminRemoved(_addr, adminIndex); } } // To Change Administrator Limit function changeAdminLimit(uint _newLimit) external { require( _newLimit >= 1 && _newLimit > adminIndex, "Limit Mismatch" ); maxAdmins = _newLimit; // Emit event emit AdminLimitChanged(maxAdmins); } // 3. STUDENTS RELATED FUNCTIONS // To Add Student function addStudent( bytes32 _firstName, bytes32 _lastName, bytes32 _commendation, grades _grade, string calldata _email ) external onlyAdmins onlyNonExistentStudents(_email) { // Add to students students[studentIndex] = Student( _firstName, _lastName, _commendation, _grade, 0, // assignmentIndex always starts with 0 true, // active defaults to true _email ); // Reverse map for look up based on email studentsReverseMapping[_email] = studentIndex; // Increment the student index studentIndex = studentIndex.add(1); // Emit event emit StudentAdded(_email, _firstName, _lastName, _commendation, _grade); } // To Remove Student function removeStudent(string calldata _email) external onlyAdmins onlyValidStudents(_email) { // update active status students[studentsReverseMapping[_email]].active = false; // Emit event emit StudentRemoved(_email); } // To Change Student Name function changeStudentName( bytes32 _firstName, bytes32 _lastName, string calldata _email ) external onlyAdmins onlyValidStudents(_email) { // Update Name students[studentsReverseMapping[_email]].firstName = _firstName; students[studentsReverseMapping[_email]].lastName = _lastName; // Emit event emit StudentNameUpdated(_email, _firstName, _lastName); } // To Change Student commendation function changeStudentCommendation( bytes32 _commendation, string calldata _email ) external onlyAdmins onlyValidStudents(_email) { // Update commendation students[studentsReverseMapping[_email]].commendation = _commendation; // Emit event emit StudentCommendationUpdated(_email, _commendation); } // To Change Student Grade function changeStudentGrade( grades _grade, string calldata _email ) external onlyAdmins onlyValidStudents(_email) { // Update Grade students[studentsReverseMapping[_email]].grade = _grade; // Emit event emit StudentGradeUpdated(_email, _grade); } // To Change Student Email function changeStudentEmail( string calldata _oldEmail, string calldata _newEmail ) external onlyAdmins onlyValidStudents(_oldEmail) onlyNonExistentStudents(_newEmail) { // update emails students[studentsReverseMapping[_oldEmail]].email = _newEmail; studentsReverseMapping[_newEmail] = studentsReverseMapping[_oldEmail]; // delete old email delete(studentsReverseMapping[_oldEmail]); // Emit event emit StudentEmailUpdated(_oldEmail, _newEmail); } // 4. ASSIGNMENT RELATED FUNCTIONS // to add a new assignment function addAssignment( string calldata _studentEmail, string calldata _link, assignmentStatus _status, bool _isFinalProject ) external onlyAdmins onlyValidStudents(_studentEmail) { // get the student Student storage stud = students[studentsReverseMapping[_studentEmail]]; // get the proper assignment ID uint16 assignmentID = _calcAndFetchAssignmentIndex(stud, _isFinalProject); // get the Assignment Assignment storage assign = stud.assignments[assignmentID]; // update it assign.link = _link; assign.status = _status; // Emit event emit AssignmentAdded(_studentEmail, _link, _status, stud.assignmentIndex); } // To update assignment status function updateAssignmentStatus( string calldata _studentEmail, assignmentStatus _status, bool _isFinalProject ) external onlyAdmins onlyValidStudents(_studentEmail) { // get the student Student storage stud = students[studentsReverseMapping[_studentEmail]]; // get the proper assignment ID uint16 assignmentID = _calcAndFetchAssignmentIndex(stud, _isFinalProject); // get the Assignment Assignment storage assign = stud.assignments[assignmentID]; // update it assign.status = _status; // Emit event emit AssignmentUpdated(_studentEmail, stud.assignmentIndex, _status); } // Private helper function to get assignment struct function _calcAndFetchAssignmentIndex( Student storage stud, bool _isFinalProject ) private returns (uint16 assignmentID) { if (!_isFinalProject) { // add to assignmentIndex and assign that as assignmentID stud.assignmentIndex = stud.assignmentIndex.add(1); assignmentID = stud.assignmentIndex; } } // Get Assignment Info function getAssignmentInfo( string calldata _studentEmail, uint16 _assignmentID ) external view onlyValidStudents(_studentEmail) returns ( string memory link, assignmentStatus status ) { // get the student Student storage stud = students[studentsReverseMapping[_studentEmail]]; // check assignment index requirement require( _assignmentID <= stud.assignmentIndex && stud.assignmentIndex >= 0, "Invalid Assignment ID" ); // get the Assignment Assignment storage assign = stud.assignments[_assignmentID]; link = assign.link; status = assign.status; } // 5. STRING / BYTE CONVERSION /** * @dev Helper Function to convert string to bytes32 format * @param _source is the string which needs to be converted * @return result is the bytes32 representation of that string */ function stringToBytes32(string memory _source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(_source); string memory tempSource = _source; if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(tempSource, 32)) } } /** * @dev Helper Function to convert bytes32 to string format * @param _x is the bytes32 format which needs to be converted * @return result is the string representation of that bytes32 string */ function bytes32ToString(bytes32 _x) public pure returns (string memory result) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(_x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } result = string(bytesStringTrimmed); } }
To Change Student Grade Update Grade Emit event
function changeStudentGrade( grades _grade, string calldata _email ) external onlyAdmins onlyValidStudents(_email) { students[studentsReverseMapping[_email]].grade = _grade; emit StudentGradeUpdated(_email, _grade); }
909,709
./partial_match/4/0x0320EBFf242764a464E59a5e14225E9739719354/sources/Inflator.sol
Deflate position by `rounds` rounds rounds Rounds to deflate (0 for full)/
function deflate(uint rounds) public auth(DEFLATE_ROLE) { deflate(rounds, address(0)); }
8,694,911
pragma solidity ^0.5.9; // See: https://github.com/ricmoo/Takoyaki ///////////////////////////// // ENS Interfaces interface Resolver { function addr(bytes32 node) external view returns (address); function setAddr(bytes32 node, address addr) external; } interface ReverseRegistrar { function claim(address owner) external returns (bytes32 node); } interface AbstractENS { function owner(bytes32 node) external view returns(address); function setOwner(bytes32 node, address owner) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setResolver(bytes32 node, address resolver) external; function resolver(bytes32 node) view external returns (address); } ///////////////////////////// // ERC-721 Interfaces interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } ///////////////////////////// // Takoyaki Registrar contract TakoyakiRegistrar { ///////////////////////////// // Constants // namehash('addr.reverse') bytes32 constant NODE_RR = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; // Must commit between (inclusive) 4 blocks (1 minute) and 5760 blocks (1 day) // Cancelling must wait for 1 hour after the commitment expired uint48 constant MIN_COMMIT_BLOCKS = (60 / 15); /*!Test: MIN_COMMIT_BLOCKS = "(60 / 15)" */ uint48 constant MAX_COMMIT_BLOCKS = (24 * 60 * 60 / 15); /*!Test: MAX_COMMIT_BLOCKS = "(24 * 60 * 60 / 15)" */ uint48 constant WAIT_CANCEL_BLOCKS = (60 * 60 / 15); /*!Test: WAIT_CANCEL_BLOCKS = "(60 * 60 / 15)" */ // A registration lasts for 1 year (a little extra for leap years) and // once expired is available to ONLY to the owner for an additional 30 days uint48 constant REGISTRATION_PERIOD = (366 days); /*!Test: REGISTRATION_PERIOD = "(366 days)" */ uint48 constant GRACE_PERIOD = (30 days); /*!Test: GRACE_PERIOD = "(30 days)" */ ///////////////////////////// // Structs struct Commitment { // The block number this commitment was made uint48 blockNumber; // These are used only for refunds address payable payer; uint256 feePaid; } struct Takoyaki { uint48 expires; uint48 commitBlockNumber; uint48 revealBlockNumber; address owner; address approved; uint256 upkeepFee; bytes32 revealedSalt; } ///////////////////////////// // Events // Registrar event Committed(address indexed funder, bytes32 commitment); event Cancelled(address indexed funder, bytes32 commitment); event Registered(address indexed owner, uint256 indexed tokenId, string label, uint48 expires); event Renewed(address indexed owner, uint256 indexed tokenId, uint48 expires); // ERC-721 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); ///////////////////////////// // State Variables // Admin address address payable private _admin; // ENS Configuration AbstractENS private _ens; bytes32 private _nodehash; Resolver private _defaultResolver; // The fee per registration period uint256 private _fee = (0.1 ether); // The commitments mapping (bytes32 => Commitment) private _commitments; // Each Takoyaki by its labelHash (id) mapping (uint256 => Takoyaki) private _takoyaki; // Balances (token count) for each owner mapping (address => uint256) private _balances; // Approval All approvals mapping (address => mapping (address => bool)) private _approveAll; uint256 private _totalSupply = 0; ///////////////////////////// // Constructor constructor(address ens, bytes32 nodehash, address defaultResolver) public { _ens = AbstractENS(ens); _nodehash = nodehash; _defaultResolver = Resolver(defaultResolver); _admin = msg.sender; // Give the admin access to the reverse entry ReverseRegistrar(_ens.owner(NODE_RR)).claim(_admin); } ///////////////////////////// // Admin functions function setAdmin(address payable newAdmin) external { require(msg.sender == _admin); _admin = newAdmin; // Give the admin access to the reverse entry ReverseRegistrar(_ens.owner(NODE_RR)).claim(_admin); } function setFee(uint newFee) external { require(msg.sender == _admin); _fee = newFee; } function setResolver(address newResolver) external { require(msg.sender == _admin); _defaultResolver = Resolver(newResolver); } function withdraw(uint256 amount) external { require(msg.sender == _admin); _admin.transfer(amount); } ///////////////////////////// // Getters for internal variables function ens() external view returns (address) { return address(_ens); } function nodehash() external view returns (bytes32) { return _nodehash; } function admin() external view returns (address) { return _admin; } function defaultResolver() external view returns (address) { return address(_defaultResolver); } function fee() external view returns (uint256) { return _fee; } // ERC-721 function totalSupply() external view returns (uint256) { return _totalSupply; } function name() external pure returns (string memory) { return "Takoyaki"; } function symbol() external pure returns (string memory) { return "TAKO"; } function decimals() external pure returns (uint8) { return 0; } function tokenURI(uint256 _tokenId) external view returns (string memory) { Takoyaki memory takoyaki = _takoyaki[_tokenId]; require(takoyaki.expires > now); string memory uri = "https://takoyaki.cafe/json/_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"; // Offset into the URI to replace. Skips // - the length prefix (32 bytes) // - the "https://takoyaki.cafe/json/" (27 bytes) uint offset = 0; assembly { offset := add(uri, 59) } // ASCII hexidecimal character lookup table uint hexLut = 0x3031323334353637383961626364656667000000000000000000000000000000; for (uint i = 0; i < 32; i++) { assembly { let value := byte(i, _tokenId) mstore8(offset, byte(shr(4, value), hexLut)) offset := add(offset, 1) mstore8(offset, byte(and(value, 0x0f), hexLut)) offset := add(offset, 1) } } return uri; } ///////////////////////////// // Label functions function fee(string calldata label) external view returns (uint256) { require(isValidLabel(label)); return _fee; } // A label is measured in bytes (not characters). A label must not begin // with a "0x" prefix (in either lowercase or uppercase). // Otherwise, valid UTF-8 data and namehash normalization (i.e. lowercase pnly) // is expected to be verified by the client. function isValidLabel(string memory label) public pure returns (bool) { bytes memory data = bytes(label); // Names MUST be between 1 byte and 20 bytes (inclusive) if (data.length < 1 || data.length > 20) { return false; } // Names MUST NOT start with "0x" or "0X" if (data.length >= 2 && data[0] == 0x30 && (data[1] | 0x20) == 0x78) { return false; } return true; } ///////////////////////////// // Commit/Reveal functions function makeBlindedCommitment(string memory label, address owner, bytes32 salt) public view returns (bytes32) { return keccak256(abi.encode(label, owner, salt)); } function getBlindedCommit(bytes32 blindedCommit) public view returns (uint48 blockNumber, address payer, uint256 feePaid) { Commitment memory commitment = _commitments[blindedCommit]; return (commitment.blockNumber, commitment.payer, commitment.feePaid); } function commit(bytes32 blindedCommit, address payable prefundRevealer, uint prefundAmount) external payable { require(msg.value == _fee + prefundAmount); Commitment storage commitment = _commitments[blindedCommit]; require(commitment.payer == address(0)); commitment.blockNumber = uint48(block.number); commitment.payer = msg.sender; commitment.feePaid = _fee; if (prefundAmount > 0) { prefundRevealer.transfer(prefundAmount); } emit Committed(msg.sender, blindedCommit); } // A commitment may be cancelled and the committed funds will be returned. // If the registrar was recently withdrawn from (by the admin) the balance // may be too low, so we revert, allowing them to try in the future once // more funds have been accumulated (if this happens to you, you may also // e-mail us to help out; [email protected]). function cancelCommitment(bytes32 blindedCommit) external { Commitment memory commitment = _commitments[blindedCommit]; require(commitment.feePaid <= address(this).balance); require(commitment.payer == msg.sender); require(block.number >= commitment.blockNumber + MAX_COMMIT_BLOCKS + WAIT_CANCEL_BLOCKS); delete _commitments[blindedCommit]; commitment.payer.transfer(commitment.feePaid); emit Cancelled(msg.sender, blindedCommit); } function reveal(string calldata label, address owner, bytes32 salt) external { require(owner != address(0)); bytes32 blindedCommit = makeBlindedCommitment(label, owner, salt); Commitment memory commitment = _commitments[blindedCommit]; require(block.number <= commitment.blockNumber + MAX_COMMIT_BLOCKS); require(block.number >= commitment.blockNumber + MIN_COMMIT_BLOCKS); // Name must be valid require(isValidLabel(label)); // Clear the precommit delete _commitments[blindedCommit]; uint256 tokenId = uint256(keccak256(bytes(label))); Takoyaki storage takoyaki = _takoyaki[tokenId]; if (takoyaki.expires == 0) { // Never registered; increase the total supply _totalSupply += 1; } else { // Was previously owned, but has expired (incuding grace period) require(takoyaki.expires < now - GRACE_PERIOD); // Was previously owned by the another address; adjust balances _balances[takoyaki.owner] -= 1; } // Update the takoyaki info; note: registering an expired takoyaki // obliterates its former existance and it is reborn takoyaki.expires = uint48(now + REGISTRATION_PERIOD); takoyaki.commitBlockNumber = commitment.blockNumber; takoyaki.revealBlockNumber = uint48(block.number); takoyaki.revealedSalt = keccak256(abi.encode(tokenId, salt)); takoyaki.owner = owner; takoyaki.upkeepFee = commitment.feePaid; takoyaki.approved = address(0); _balances[owner] += 1; // ENS node bytes32 nodehash = keccak256(abi.encode(_nodehash, tokenId)); // Make this registrar the owner (so we can set it up before giving it away) _ens.setSubnodeOwner(_nodehash, bytes32(tokenId), address(this)); // Set up the default resolver and point to the sender _ens.setResolver(nodehash, address(_defaultResolver)); _defaultResolver.setAddr(nodehash, owner); // Now give it to the new owner _ens.setOwner(nodehash, owner); emit Registered(owner, tokenId, label, takoyaki.expires); emit Transfer(address(0), owner, tokenId); } // Not really necessary, but maybe someone wants to keep totalSupply correct // or really hates a specific Takoyaki function destroy(uint256 tokenId) external { Takoyaki memory takoyaki = _takoyaki[tokenId]; require(takoyaki.owner != address(0)); require(takoyaki.expires < now - GRACE_PERIOD); _balances[takoyaki.owner] -= 1; delete _takoyaki[tokenId]; _totalSupply -= 1; _ens.setSubnodeOwner(_nodehash, bytes32(tokenId), address(0)); emit Transfer(takoyaki.owner, address(0), tokenId); } /** * Allow a Takoyaki owner to lock-in the current upkeep fee, if it * is lower than their current upkeep fee. * * Anyone may call this. */ function syncUpkeepFee(uint256 tokenId) external { Takoyaki storage takoyaki = _takoyaki[tokenId]; require(takoyaki.owner != address(0)); require(takoyaki.expires > now); // If the fee has decreased, set this Takoyyaki as the new lower fee if (_fee < takoyaki.upkeepFee) { takoyaki.upkeepFee = _fee; } } // A Takoyaki has an upkeep cost. The upkeep will never be more than the // fee originally paid for a takoyaki, but if the fee has decreased, the // new (lower) fee is set as the new fee. function renew(uint256 tokenId) external payable { Takoyaki storage takoyaki = _takoyaki[tokenId]; require(takoyaki.owner != address(0)); // Must not be expired or outside of grace period require(takoyaki.expires > (now - GRACE_PERIOD)); // If the fee has decreased, set this Takoyaki upkeep fee as the new lower fee if (_fee < takoyaki.upkeepFee) { takoyaki.upkeepFee = _fee; } require(msg.value == takoyaki.upkeepFee); // Prevent super long registration; upkeep must be semi-periodic require(takoyaki.expires < now + (2 * REGISTRATION_PERIOD)); // Extend by the registration period takoyaki.expires += REGISTRATION_PERIOD; emit Renewed(takoyaki.owner, tokenId, takoyaki.expires); } // Reset the registrant as the controller function reclaim(uint256 tokenId, address owner) external { Takoyaki memory takoyaki = _takoyaki[tokenId]; require(msg.sender == takoyaki.owner && takoyaki.expires > now); _ens.setSubnodeOwner(_nodehash, bytes32(tokenId), owner); } ///////////////////////////// // Takoyaki functions // Used to derive the appearance and metadata of the Takoyaki // - The revealedSalt + blockhash(commitBlockNumber + X) is used for the appearance // - The revealBlockNumber simplifies clients attempting to lookup the unhashed label // - The expires date is useful for UI // - The status has more information about the current registration status function getTakoyaki(uint256 tokenId) external view returns (bytes32 revealSeed, address owner, uint256 upkeepFee, uint48 commitBlock, uint48 revealBlock, uint48 expires, uint8 status) { // Status: // 0: Available // 1: Grace period // 2: Registered uint8 status = 2; if (_takoyaki[tokenId].expires < now - GRACE_PERIOD) { status = 0; } else if (_takoyaki[tokenId].expires < now) { status = 1; } Takoyaki storage takoyaki = _takoyaki[tokenId]; return (takoyaki.revealedSalt, takoyaki.owner, takoyaki.upkeepFee, takoyaki.commitBlockNumber, takoyaki.revealBlockNumber, takoyaki.expires, status); } ///////////////////////////// // ERC-721 Implementation function ownerOf(uint256 tokenId) public view returns (address) { Takoyaki memory takoyaki = _takoyaki[tokenId]; require(takoyaki.expires > now); return takoyaki.owner; } // Note: Expired tokens will still count towards the balance; use destroy to sync function balanceOf(address owner) external view returns (uint256) { require(owner != address(0)); return _balances[owner]; } function approve(address to, uint256 tokenId) external { Takoyaki storage takoyaki = _takoyaki[tokenId]; //require(takoyaki.owner != to); Why does the OpenZepplin implementation assert this? require(msg.sender == takoyaki.owner || isApprovedForAll(takoyaki.owner, msg.sender)); require(takoyaki.expires > now); takoyaki.approved = to; emit Approval(takoyaki.owner, to, tokenId); } function getApproved(uint256 tokenId) external view returns (address) { Takoyaki memory takoyaki = _takoyaki[tokenId]; // I think there is a bug in the OpenZepplin implt; it throws if the address is // zero, but the ERC-721 spec speficies 0 is valid to indicate no approved... require(takoyaki.expires > now); return takoyaki.approved; } function setApprovalForAll(address to, bool approved) external { //require(to != msg.sender); Why does OpenZepplin enforce this? _approveAll[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } function isApprovedForAll(address owner, address operator) public view returns (bool) { return _approveAll[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public { require(to != address(0)); Takoyaki storage takoyaki = _takoyaki[tokenId]; require(takoyaki.owner == from); require(takoyaki.expires > now); require(msg.sender == takoyaki.owner || msg.sender == takoyaki.approved || isApprovedForAll(takoyaki.owner, msg.sender)); if (takoyaki.owner != to) { _balances[takoyaki.owner] -= 1; _balances[to] += 1; } emit Transfer(takoyaki.owner, to, tokenId); takoyaki.owner = to; takoyaki.approved = address(0); // @TODO: Should we do this for a transfer?? bytes32 nodehash = keccak256(abi.encode(_nodehash, tokenId)); // Make this registrar the owner (so we can set it up before giving it away) _ens.setSubnodeOwner(_nodehash, bytes32(tokenId), address(this)); // Set up the default resolver and point to the sender _ens.setResolver(nodehash, address(_defaultResolver)); _defaultResolver.setAddr(nodehash, to); // Now give it to the new owner _ens.setOwner(nodehash, to); } function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } // ERC-721 Safe Transfer: 0x150b7a02 bytes4 constant private ERC721_TOKEN_RECEIVER_ID = bytes4( keccak256("onERC721Received(address,address,uint256,bytes)") ); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); // If there is a contract currently at this address, call its // onERC721Received method and make sure it returns uint256 codeSize; assembly { codeSize := extcodesize(to) } if (codeSize > 0) { bytes4 result = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) require(result == ERC721_TOKEN_RECEIVER_ID); } } ///////////////////////////// // ERC-165 // ERC-165: 0x01ffc9a7 bytes4 constant private INTERFACE_META_ID = bytes4( keccak256("supportsInterface(bytes4)") ); // ERC-721: 0x80ac58cd bytes4 constant private ERC721_ID = bytes4( keccak256("balanceOf(address)") ^ keccak256("ownerOf(uint256)") ^ keccak256("approve(address,uint256)") ^ keccak256("getApproved(uint256)") ^ keccak256("setApprovalForAll(address,bool)") ^ keccak256("isApprovedForAll(address,address)") ^ keccak256("transferFrom(address,address,uint256)") ^ keccak256("safeTransferFrom(address,address,uint256)") ^ keccak256("safeTransferFrom(address,address,uint256,bytes)") ); // ERC-721 Metadata Extension: 0x5b5e139f bytes4 constant private ERC721_METAEXT_ID = bytes4( keccak256("name()") ^ keccak256("symbol()") ^ keccak256("tokenURI(uint256)") ); // ENS Registrar Extension: 0x28ed4f6c // See: https://github.com/ensdomains/ethregistrar/blob/master/contracts/BaseRegistrarImplementation.sol#L27 bytes4 constant private RECLAIM_ID = bytes4( keccak256("reclaim(uint256,address)") ); // ERC-165 function supportsInterface(bytes4 interfaceID) public view returns (bool) { return ( interfaceID == INTERFACE_META_ID || interfaceID == ERC721_ID || interfaceID == ERC721_METAEXT_ID || interfaceID == RECLAIM_ID ); } }
Note: Expired tokens will still count towards the balance; use destroy to sync
function balanceOf(address owner) external view returns (uint256) { require(owner != address(0)); return _balances[owner]; }
13,102,116
./partial_match/1/0x81859801b01764D4f0Fa5E64729f5a6C3b91435b/sources/BearnTokenERC20.sol
Can be called by only Gateway
function mint(address _to, uint _amount) external onlyOwner { _mint(_to, _amount); }
3,551,675
./partial_match/42/0xc50aE2019Cdb65FC4B12E88cc0a0896eC745cd43/sources/InDefiEcoPreMining.sol
allow to claim profit from tokenized startegy (in new version)
function defiController() view external returns(address) { return owner; }
3,475,114
pragma solidity ^0.5.0; interface ICustodian { function users(uint) external returns(address); function totalUsers() external returns (uint); function totalSupplyA() external returns (uint); function totalSupplyB() external returns (uint); function balanceOf(uint, address) external returns (uint); function allowance(uint, address, address) external returns (uint); function transfer(uint, address, address, uint) external returns (bool); function transferFrom(uint, address, address, address, uint) external returns (bool); function approve(uint, address, address, uint) external returns (bool); } /// @title Esplanade - coordinate multiple custodians, oracles and other contracts. /// @author duo.network contract Esplanade { /* * Constants */ uint constant WEI_DENOMINATOR = 1000000000000000000; uint constant BP_DENOMINATOR = 10000; uint constant MIN_POOL_SIZE = 5; uint constant VOTE_TIME_OUT = 2 hours; uint constant COLD_POOL_IDX = 0; uint constant HOT_POOL_IDX = 1; uint constant NEW_STATUS = 0; uint constant IN_COLD_POOL_STATUS = 1; uint constant IN_HOT_POOL_STATUS = 2; uint constant USED_STATUS = 3; enum VotingStage { NotStarted, Moderator, Contract } /* * Storage */ VotingStage public votingStage; address public moderator; // 0 is cold // 1 is hot address [][] public addrPool =[ [ 0xAc31E7Bc5F730E460C6B2b50617F421050265ece, 0x39426997B2B5f0c8cad0C6e571a2c02A6510d67b, 0x292B0E0060adBa58cCA9148029a79D5496950c9D, 0x835B8D6b7b62240000491f7f0B319204BD5dDB25, 0x8E0E4DE505ee21ECA63fAF762B48D774E8BB8f51, 0x8750A35A4FB67EE5dE3c02ec35d5eA59193034f5, 0x8849eD77E94B075D89bB67D8ef98D80A8761d913, 0x2454Da2d95FBA41C3a901D8ce69D0fdC8dA8274e, 0x56F08EE15a4CBB8d35F82a44d288D08F8b924c8b ], [ 0x709494F5766a7e280A24cF15e7feBA9fbadBe7F5, 0xF7029296a1dA0388b0b637127F241DD11901f2af, 0xE266581CDe8468915D9c9F42Be3DcEd51db000E0, 0x37c521F852dbeFf9eC93991fFcE91b2b836Ad549, 0x2fEF2469937EeA7B126bC888D8e02d762D8c7e16, 0x249c1daD9c31475739fBF08C95C2DCB137135957, 0x8442Dda926BFb4Aeba526D4d1e8448c762cf4A0c, 0xe71DA90BC3cb2dBa52bacfBbA7b973260AAAFc05, 0xd3FA38302b0458Bf4E1405D209F30db891eBE038 ] ]; // 0 is new address // 1 in cold pool // 2 in hot pool // 3 is used mapping(address => uint) public addrStatus; address[] public custodianPool; mapping(address => bool) public existingCustodians; address[] public otherContractPool; mapping(address => bool) public existingOtherContracts; uint public operatorCoolDown = 1 hours; uint public lastOperationTime; bool public started; address public candidate; mapping(address => bool) public passedContract; mapping(address => bool) public voted; uint public votedFor; uint public votedAgainst; uint public voteStartTimestamp; /* * Modifiers */ modifier only(address addr) { require(msg.sender == addr); _; } modifier inColdAddrPool() { require(addrStatus[msg.sender] == IN_COLD_POOL_STATUS); _; } modifier inHotAddrPool() { require(addrStatus[msg.sender] == IN_HOT_POOL_STATUS); _; } modifier isValidRequestor(address origin) { address requestorAddr = msg.sender; require((existingCustodians[requestorAddr] || existingOtherContracts[requestorAddr]) && addrStatus[origin] == IN_COLD_POOL_STATUS); _; } modifier inUpdateWindow() { uint currentTime = getNowTimestamp(); if (started) require(currentTime - lastOperationTime >= operatorCoolDown); _; lastOperationTime = currentTime; } modifier inVotingStage(VotingStage _stage) { require(votingStage == _stage); _; } modifier allowedToVote() { address voterAddr = msg.sender; require(!voted[voterAddr] && addrStatus[voterAddr] == 1); _; } /* * Events */ event AddAddress(uint poolIndex, address added1, address added2); event RemoveAddress(uint poolIndex, address addr); event ProvideAddress(uint poolIndex, address requestor, address origin, address addr); event AddCustodian(address newCustodianAddr); event AddOtherContract(address newContractAddr); event StartContractVoting(address proposer, address newContractAddr); event TerminateContractVoting(address terminator, address currentCandidate); event StartModeratorVoting(address proposer); event TerminateByTimeOut(address candidate); event Vote(address voter, address candidate, bool voteFor, uint votedFor, uint votedAgainst); event CompleteVoting(bool isContractVoting, address newAddress); event ReplaceModerator(address oldModerator, address newModerator); /* * Constructor */ /// @dev Contract constructor sets operation cool down and set address pool status. /// @param optCoolDown operation cool down time. constructor(uint optCoolDown) public { votingStage = VotingStage.NotStarted; moderator = msg.sender; addrStatus[moderator] = USED_STATUS; for (uint i = 0; i < addrPool[COLD_POOL_IDX].length; i++) addrStatus[addrPool[COLD_POOL_IDX][i]] = IN_COLD_POOL_STATUS; for (uint j = 0; j < addrPool[HOT_POOL_IDX].length; j++) addrStatus[addrPool[HOT_POOL_IDX][j]] = IN_HOT_POOL_STATUS; operatorCoolDown = optCoolDown; } /* * MultiSig Management */ /// @dev proposeNewManagerContract function. /// @param addr new manager contract address proposed. function startContractVoting(address addr) public only(moderator) inVotingStage(VotingStage.NotStarted) returns (bool) { require(addrStatus[addr] == NEW_STATUS); candidate = addr; addrStatus[addr] = USED_STATUS; votingStage = VotingStage.Contract; replaceModerator(); startVoting(); emit StartContractVoting(moderator, addr); return true; } /// @dev terminateVoting function. function terminateContractVoting() public only(moderator) inVotingStage(VotingStage.Contract) returns (bool) { votingStage = VotingStage.NotStarted; emit TerminateContractVoting(moderator, candidate); replaceModerator(); return true; } /// @dev terminateVoting voting if timeout function terminateByTimeout() public returns (bool) { require(votingStage != VotingStage.NotStarted); uint nowTimestamp = getNowTimestamp(); if (nowTimestamp > voteStartTimestamp && nowTimestamp - voteStartTimestamp > VOTE_TIME_OUT) { votingStage = VotingStage.NotStarted; emit TerminateByTimeOut(candidate); return true; } else return false; } /// @dev proposeNewModerator function. function startModeratorVoting() public inColdAddrPool() returns (bool) { candidate = msg.sender; votingStage = VotingStage.Moderator; removeFromPoolByAddr(COLD_POOL_IDX, candidate); startVoting(); emit StartModeratorVoting(candidate); return true; } /// @dev proposeNewModerator function. function vote(bool voteFor) public allowedToVote() returns (bool) { address voter = msg.sender; if (voteFor) votedFor = votedFor + 1; else votedAgainst += 1; voted[voter] = true; uint threshold = addrPool[COLD_POOL_IDX].length / 2; emit Vote(voter, candidate, voteFor, votedFor, votedAgainst); if (votedFor > threshold || votedAgainst > threshold) { if (votingStage == VotingStage.Contract) { passedContract[candidate] = true; emit CompleteVoting(true, candidate); } else { emit CompleteVoting(false, candidate); moderator = candidate; } votingStage = VotingStage.NotStarted; } return true; } /* * Moderator Public functions */ /// @dev start roleManagerContract. function startManager() public only(moderator) returns (bool) { require(!started && custodianPool.length > 0); started = true; return true; } /// @dev addCustodian function. /// @param custodianAddr custodian address to add. function addCustodian(address custodianAddr) public only(moderator) inUpdateWindow() returns (bool success) { require(!existingCustodians[custodianAddr] && !existingOtherContracts[custodianAddr]); ICustodian custodian = ICustodian(custodianAddr); require(custodian.totalUsers() >= 0); // custodian.users(0); uint custodianLength = custodianPool.length; if (custodianLength > 0) replaceModerator(); else if (!started) { uint index = getNextAddrIndex(COLD_POOL_IDX, custodianAddr); address oldModerator = moderator; moderator = addrPool[COLD_POOL_IDX][index]; emit ReplaceModerator(oldModerator, moderator); removeFromPool(COLD_POOL_IDX, index); } existingCustodians[custodianAddr] = true; custodianPool.push(custodianAddr); addrStatus[custodianAddr] = USED_STATUS; emit AddCustodian(custodianAddr); return true; } /// @dev addOtherContracts function. /// @param contractAddr other contract address to add. function addOtherContracts(address contractAddr) public only(moderator) inUpdateWindow() returns (bool success) { require(!existingCustodians[contractAddr] && !existingOtherContracts[contractAddr]); existingOtherContracts[contractAddr] = true; otherContractPool.push(contractAddr); addrStatus[contractAddr] = USED_STATUS; replaceModerator(); emit AddOtherContract(contractAddr); return true; } /// @dev add two addreess into pool function. /// @param addr1 the first address /// @param addr2 the second address. /// @param poolIndex indicate adding to hot or cold. function addAddress(address addr1, address addr2, uint poolIndex) public only(moderator) inUpdateWindow() returns (bool success) { require(addrStatus[addr1] == NEW_STATUS && addrStatus[addr2] == NEW_STATUS && addr1 != addr2 && poolIndex < 2); replaceModerator(); addrPool[poolIndex].push(addr1); addrStatus[addr1] = poolIndex + 1; addrPool[poolIndex].push(addr2); addrStatus[addr2] = poolIndex + 1; emit AddAddress(poolIndex, addr1, addr2); return true; } /// @dev removeAddress function. /// @param addr the address to remove from /// @param poolIndex the pool to remove from. function removeAddress(address addr, uint poolIndex) public only(moderator) inUpdateWindow() returns (bool success) { require(addrPool[poolIndex].length > MIN_POOL_SIZE && addrStatus[addr] == poolIndex + 1 && poolIndex < 2); removeFromPoolByAddr(poolIndex, addr); replaceModerator(); emit RemoveAddress(poolIndex, addr); return true; } /// @dev provide address to other contracts, such as custodian, oracle and others. /// @param origin the origin who makes request /// @param poolIndex the pool to request address from. function provideAddress(address origin, uint poolIndex) public isValidRequestor(origin) inUpdateWindow() returns (address) { require(addrPool[poolIndex].length > MIN_POOL_SIZE && poolIndex < 2 && custodianPool.length > 0); removeFromPoolByAddr(COLD_POOL_IDX, origin); address requestor = msg.sender; uint index = 0; // is custodian if (existingCustodians[requestor]) index = getNextAddrIndex(poolIndex, requestor); else // is other contract; index = getNextAddrIndex(poolIndex, custodianPool[custodianPool.length - 1]); address addr = addrPool[poolIndex][index]; removeFromPool(poolIndex, index); emit ProvideAddress(poolIndex, requestor, origin, addr); return addr; } /* * Internal functions */ function startVoting() internal { address[] memory coldPool = addrPool[COLD_POOL_IDX]; for (uint i = 0; i < coldPool.length; i++) voted[coldPool[i]] = false; votedFor = 0; votedAgainst = 0; voteStartTimestamp = getNowTimestamp(); } function replaceModerator() internal { require(custodianPool.length > 0); uint index = getNextAddrIndex(COLD_POOL_IDX, custodianPool[custodianPool.length - 1]); address oldModerator = moderator; moderator = addrPool[COLD_POOL_IDX][index]; emit ReplaceModerator(oldModerator, moderator); removeFromPool(COLD_POOL_IDX, index); } /// @dev removeFromPool Function. /// @param poolIndex the pool to request from removal. /// @param addr the address to remove function removeFromPoolByAddr(uint poolIndex, address addr) internal { address[] memory subPool = addrPool[poolIndex]; for (uint i = 0; i < subPool.length; i++) { if (subPool[i] == addr) { removeFromPool(poolIndex, i); break; } } } /// @dev removeFromPool Function. /// @param poolIndex the pool to request from removal. /// @param idx the index of address to remove function removeFromPool(uint poolIndex, uint idx) internal { address[] memory subPool = addrPool[poolIndex]; addrStatus[subPool[idx]] = USED_STATUS; if (idx < subPool.length - 1) addrPool[poolIndex][idx] = addrPool[poolIndex][subPool.length-1]; delete addrPool[poolIndex][subPool.length - 1]; // emit RemoveFromPool(poolIndex, addrPool[poolIndex][idx]); addrPool[poolIndex].length--; } /// @dev getNextAddrIndex Function. /// @param poolIndex the pool to request address from. /// @param custodianAddr the index of custodian contract address for randomeness generation function getNextAddrIndex(uint poolIndex, address custodianAddr) internal returns (uint) { uint prevHashNumber = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1)))); ICustodian custodian = ICustodian(custodianAddr); uint userLength = custodian.totalUsers(); if(userLength > 255) { address randomUserAddress = custodian.users(prevHashNumber % userLength); return uint256(keccak256(abi.encodePacked(randomUserAddress))) % addrPool[poolIndex].length; } else return prevHashNumber % addrPool[poolIndex].length; } /// @dev get Ethereum blockchain current timestamp function getNowTimestamp() internal view returns (uint) { return now; } /// @dev get addressPool size function getAddressPoolSizes() public view returns (uint, uint) { return (addrPool[COLD_POOL_IDX].length, addrPool[HOT_POOL_IDX].length); } /// @dev get contract pool size function getContractPoolSizes() public view returns (uint, uint) { return (custodianPool.length, otherContractPool.length); } }
get Ethereum blockchain current timestamp
function getNowTimestamp() internal view returns (uint) { return now; }
12,803,797
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TradingAction.sol"; import "./ActionGuards.sol"; import "./nTokenMintAction.sol"; import "./nTokenRedeemAction.sol"; import "../SettleAssetsExternal.sol"; import "../FreeCollateralExternal.sol"; import "../../math/SafeInt256.sol"; import "../../global/StorageLayoutV1.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/AccountContextHandler.sol"; import "../../../interfaces/notional/NotionalCallback.sol"; contract BatchAction is StorageLayoutV1, ActionGuards { using BalanceHandler for BalanceState; using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; using SafeInt256 for int256; /// @notice Executes a batch of balance transfers including minting and redeeming nTokens. /// @param account the account for the action /// @param actions array of balance actions to take, must be sorted by currency id /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange /// @dev auth:msg.sender auth:ERC1155 function batchBalanceAction(address account, BalanceAction[] calldata actions) external payable nonReentrant { require(account == msg.sender || msg.sender == address(this), "Unauthorized"); requireValidAccount(account); // Return any settle amounts here to reduce the number of storage writes to balances AccountContext memory accountContext = _settleAccountIfRequired(account); BalanceState memory balanceState; for (uint256 i = 0; i < actions.length; i++) { BalanceAction calldata action = actions[i]; // msg.value will only be used when currency id == 1, referencing ETH. The requirement // to sort actions by increasing id enforces that msg.value will only be used once. if (i > 0) { require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions"); } // Loads the currencyId into balance state balanceState.loadBalanceState(account, action.currencyId, accountContext); _executeDepositAction( account, balanceState, action.actionType, action.depositActionAmount ); _calculateWithdrawActionAndFinalize( account, accountContext, balanceState, action.withdrawAmountInternalPrecision, action.withdrawEntireCashBalance, action.redeemToUnderlying ); } _finalizeAccountContext(account, accountContext); } /// @notice Executes a batch of balance transfers and trading actions /// @param account the account for the action /// @param actions array of balance actions with trades to take, must be sorted by currency id /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity, /// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued /// @dev auth:msg.sender auth:ERC1155 function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions) external payable nonReentrant { require(account == msg.sender || msg.sender == address(this), "Unauthorized"); requireValidAccount(account); AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions); _finalizeAccountContext(account, accountContext); } /// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This /// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform /// other actions on behalf of the user. /// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract /// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM /// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting /// and will mainly be used for contracts that make migrating assets a better user experience. /// @param account the account that will take all the actions /// @param actions array of balance actions with trades to take, must be sorted by currency id /// @param callbackData arbitrary bytes to be passed backed to the caller in the callback /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity, /// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued /// @dev auth:authorizedCallbackContract function batchBalanceAndTradeActionWithCallback( address account, BalanceActionWithTrades[] calldata actions, bytes calldata callbackData ) external payable { // NOTE: Re-entrancy is allowed for authorized callback functions. require(authorizedCallbackContract[msg.sender], "Unauthorized"); requireValidAccount(account); AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions); accountContext.setAccountContext(account); // Be sure to set the account context before initiating the callback, all stateful updates // have been finalized at this point so we are safe to issue a callback. This callback may // re-enter Notional safely to deposit or take other actions. NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData); if (accountContext.hasDebt != 0x00) { // NOTE: this method may update the account context to turn off the hasDebt flag, this // is ok because the worst case would be causing an extra free collateral check when it // is not required. This check will be entered if the account hasDebt prior to the callback // being triggered above, so it will happen regardless of what the callback function does. FreeCollateralExternal.checkFreeCollateralAndRevert(account); } } function _batchBalanceAndTradeAction( address account, BalanceActionWithTrades[] calldata actions ) internal returns (AccountContext memory) { AccountContext memory accountContext = _settleAccountIfRequired(account); BalanceState memory balanceState; // NOTE: loading the portfolio state must happen after settle account to get the // correct portfolio, it will have changed if the account is settled. PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); for (uint256 i = 0; i < actions.length; i++) { BalanceActionWithTrades calldata action = actions[i]; // msg.value will only be used when currency id == 1, referencing ETH. The requirement // to sort actions by increasing id enforces that msg.value will only be used once. if (i > 0) { require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions"); } // Loads the currencyId into balance state balanceState.loadBalanceState(account, action.currencyId, accountContext); // Does not revert on invalid action types here, they also have no effect. _executeDepositAction( account, balanceState, action.actionType, action.depositActionAmount ); if (action.trades.length > 0) { int256 netCash; if (accountContext.isBitmapEnabled()) { require( accountContext.bitmapCurrencyId == action.currencyId, "Invalid trades for account" ); bool didIncurDebt; (netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, action.trades ); if (didIncurDebt) { accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt; } } else { // NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch // because we want to only write to storage once after all trades are completed (portfolioState, netCash) = TradingAction.executeTradesArrayBatch( account, action.currencyId, portfolioState, action.trades ); } // If the account owes cash after trading, ensure that it has enough if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg()); balanceState.netCashChange = balanceState.netCashChange.add(netCash); } _calculateWithdrawActionAndFinalize( account, accountContext, balanceState, action.withdrawAmountInternalPrecision, action.withdrawEntireCashBalance, action.redeemToUnderlying ); } // Update the portfolio state if bitmap is not enabled. If bitmap is already enabled // then all the assets have already been updated in in storage. if (!accountContext.isBitmapEnabled()) { // NOTE: account context is updated in memory inside this method call. accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } // NOTE: free collateral and account context will be set outside of this method call. return accountContext; } /// @dev Executes deposits function _executeDepositAction( address account, BalanceState memory balanceState, DepositActionType depositType, uint256 depositActionAmount_ ) private { int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_); int256 assetInternalAmount; require(depositActionAmount >= 0); if (depositType == DepositActionType.None) { return; } else if ( depositType == DepositActionType.DepositAsset || depositType == DepositActionType.DepositAssetAndMintNToken ) { // NOTE: this deposit will NOT revert on a failed transfer unless there is a // transfer fee. The actual transfer will take effect later in balanceState.finalize assetInternalAmount = balanceState.depositAssetToken( account, depositActionAmount, false // no force transfer ); } else if ( depositType == DepositActionType.DepositUnderlying || depositType == DepositActionType.DepositUnderlyingAndMintNToken ) { // NOTE: this deposit will revert on a failed transfer immediately assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount); } else if (depositType == DepositActionType.ConvertCashToNToken) { // _executeNTokenAction will check if the account has sufficient cash assetInternalAmount = depositActionAmount; } _executeNTokenAction( balanceState, depositType, depositActionAmount, assetInternalAmount ); } /// @dev Executes nToken actions function _executeNTokenAction( BalanceState memory balanceState, DepositActionType depositType, int256 depositActionAmount, int256 assetInternalAmount ) private { // After deposits have occurred, check if we are minting nTokens if ( depositType == DepositActionType.DepositAssetAndMintNToken || depositType == DepositActionType.DepositUnderlyingAndMintNToken || depositType == DepositActionType.ConvertCashToNToken ) { // Will revert if trying to mint ntokens and results in a negative cash balance _checkSufficientCash(balanceState, assetInternalAmount); balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount); // Converts a given amount of cash (denominated in internal precision) into nTokens int256 tokensMinted = nTokenMintAction.nTokenMint( balanceState.currencyId, assetInternalAmount ); balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add( tokensMinted ); } else if (depositType == DepositActionType.RedeemNToken) { require( // prettier-ignore balanceState .storedNTokenBalance .add(balanceState.netNTokenTransfer) // transfers would not occur at this point .add(balanceState.netNTokenSupplyChange) >= depositActionAmount, "Insufficient token balance" ); balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub( depositActionAmount ); int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch( balanceState.currencyId, depositActionAmount ); balanceState.netCashChange = balanceState.netCashChange.add(assetCash); } } /// @dev Calculations any withdraws and finalizes balances function _calculateWithdrawActionAndFinalize( address account, AccountContext memory accountContext, BalanceState memory balanceState, uint256 withdrawAmountInternalPrecision, bool withdrawEntireCashBalance, bool redeemToUnderlying ) private { int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision); require(withdrawAmount >= 0); // dev: withdraw action overflow // NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input if (withdrawEntireCashBalance) { // This option is here so that accounts do not end up with dust after lending since we generally // cannot calculate exact cash amounts from the liquidity curve. withdrawAmount = balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision); // If the account has a negative cash balance then cannot withdraw if (withdrawAmount < 0) withdrawAmount = 0; } // prettier-ignore balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .sub(withdrawAmount); balanceState.finalize(account, accountContext, redeemToUnderlying); } function _finalizeAccountContext(address account, AccountContext memory accountContext) private { // At this point all balances, market states and portfolio states should be finalized. Just need to check free // collateral if required. accountContext.setAccountContext(account); if (accountContext.hasDebt != 0x00) { FreeCollateralExternal.checkFreeCollateralAndRevert(account); } } /// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance /// to do so. function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision) private pure { // The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision require( amountInternalPrecision >= 0 && balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision, "Insufficient cash" ); } function _settleAccountIfRequired(address account) private returns (AccountContext memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { // Returns a new memory reference to account context return SettleAssetsExternal.settleAccount(account, accountContext); } else { return accountContext; } } /// @notice Get a list of deployed library addresses (sorted by library name) function getLibInfo() external view returns (address, address, address, address, address, address) { return ( address(FreeCollateralExternal), address(MigrateIncentives), address(SettleAssetsExternal), address(TradingAction), address(nTokenMintAction), address(nTokenRedeemAction) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../FreeCollateralExternal.sol"; import "../SettleAssetsExternal.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/portfolio/TransferAssets.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library TradingAction { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; using Market for MarketParameters; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; using SafeInt256 for int256; using SafeMath for uint256; event LendBorrowTrade( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash ); event AddRemoveLiquidity( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash, int256 netLiquidityTokens ); event SettledCashDebt( address indexed settledAccount, uint16 indexed currencyId, address indexed settler, int256 amountToSettleAsset, int256 fCashAmount ); event nTokenResidualPurchase( uint16 indexed currencyId, uint40 indexed maturity, address indexed purchaser, int256 fCashAmountToPurchase, int256 netAssetCashNToken ); /// @dev Used internally to manage stack issues struct TradeContext { int256 cash; int256 fCashAmount; int256 fee; int256 netCash; int256 totalFee; uint256 blockTime; } /// @notice Executes trades for a bitmapped portfolio, cannot be called directly /// @param account account to put fCash assets in /// @param bitmapCurrencyId currency id of the bitmap /// @param nextSettleTime used to calculate the relative positions in the bitmap /// @param trades tightly packed array of trades, schema is defined in global/Types.sol /// @return netCash generated by trading /// @return didIncurDebt if the bitmap had an fCash position go negative function executeTradesBitmapBatch( address account, uint16 bitmapCurrencyId, uint40 nextSettleTime, bytes32[] calldata trades ) external returns (int256, bool) { CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId); MarketParameters memory market; bool didIncurDebt; TradeContext memory c; c.blockTime = block.timestamp; for (uint256 i = 0; i < trades.length; i++) { uint256 maturity; (maturity, c.cash, c.fCashAmount) = _executeTrade( account, cashGroup, market, trades[i], c.blockTime ); c.fCashAmount = BitmapAssetsHandler.addifCashAsset( account, bitmapCurrencyId, maturity, nextSettleTime, c.fCashAmount ); didIncurDebt = didIncurDebt || (c.fCashAmount < 0); c.netCash = c.netCash.add(c.cash); } return (c.netCash, didIncurDebt); } /// @notice Executes trades for a bitmapped portfolio, cannot be called directly /// @param account account to put fCash assets in /// @param currencyId currency id to trade /// @param portfolioState used to update the positions in the portfolio /// @param trades tightly packed array of trades, schema is defined in global/Types.sol /// @return resulting portfolio state /// @return netCash generated by trading function executeTradesArrayBatch( address account, uint16 currencyId, PortfolioState memory portfolioState, bytes32[] calldata trades ) external returns (PortfolioState memory, int256) { CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId); MarketParameters memory market; TradeContext memory c; c.blockTime = block.timestamp; for (uint256 i = 0; i < trades.length; i++) { TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i])))); if ( tradeType == TradeActionType.AddLiquidity || tradeType == TradeActionType.RemoveLiquidity ) { revert("Disabled"); /** * Manual adding and removing of liquidity is currently disabled. * * // Liquidity tokens can only be added by array portfolio * c.cash = _executeLiquidityTrade( * account, * cashGroup, * market, * tradeType, * trades[i], * portfolioState, * c.netCash * ); */ } else { uint256 maturity; (maturity, c.cash, c.fCashAmount) = _executeTrade( account, cashGroup, market, trades[i], c.blockTime ); portfolioState.addAsset( currencyId, maturity, Constants.FCASH_ASSET_TYPE, c.fCashAmount ); } c.netCash = c.netCash.add(c.cash); } return (portfolioState, c.netCash); } /// @notice Executes a non-liquidity token trade /// @param account the initiator of the trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param trade bytes32 encoding of the particular trade /// @param blockTime the current block time /// @return maturity of the asset that was traded /// @return cashAmount - a positive or negative cash amount accrued to the account /// @return fCashAmount - a positive or negative fCash amount accrued to the account function _executeTrade( address account, CashGroupParameters memory cashGroup, MarketParameters memory market, bytes32 trade, uint256 blockTime ) private returns ( uint256 maturity, int256 cashAmount, int256 fCashAmount ) { TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade)))); if (tradeType == TradeActionType.PurchaseNTokenResidual) { (maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual( account, cashGroup, blockTime, trade ); } else if (tradeType == TradeActionType.SettleCashDebt) { (maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade); } else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) { (cashAmount, fCashAmount) = _executeLendBorrowTrade( cashGroup, market, tradeType, blockTime, trade ); // This is a little ugly but required to deal with stack issues. We know the market is loaded // with the proper maturity inside _executeLendBorrowTrade maturity = market.maturity; emit LendBorrowTrade( account, uint16(cashGroup.currencyId), uint40(maturity), cashAmount, fCashAmount ); } else { revert("Invalid trade type"); } } /// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold /// liquidity tokens. /// @param account the initiator of the trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param tradeType whether this is add or remove liquidity /// @param trade bytes32 encoding of the particular trade /// @param portfolioState the current account's portfolio state /// @param netCash the current net cash accrued in this batch of trades, can be // used for adding liquidity /// @return cashAmount: a positive or negative cash amount accrued to the account function _executeLiquidityTrade( address account, CashGroupParameters memory cashGroup, MarketParameters memory market, TradeActionType tradeType, bytes32 trade, PortfolioState memory portfolioState, int256 netCash ) private returns (int256) { uint256 marketIndex = uint8(bytes1(trade << 8)); // NOTE: this loads the market in memory cashGroup.loadMarket(market, marketIndex, true, block.timestamp); int256 cashAmount; int256 fCashAmount; int256 tokens; if (tradeType == TradeActionType.AddLiquidity) { cashAmount = int256((uint256(trade) >> 152) & type(uint88).max); // Setting cash amount to zero will deposit all net cash accumulated in this trade into // liquidity. This feature allows accounts to borrow in one maturity to provide liquidity // in another in a single transaction without dust. It also allows liquidity providers to // sell off the net cash residuals and use the cash amount in the new market without dust if (cashAmount == 0) cashAmount = netCash; // Add liquidity will check cash amount is positive (tokens, fCashAmount) = market.addLiquidity(cashAmount); cashAmount = cashAmount.neg(); // Report a negative cash amount in the event } else { tokens = int256((uint256(trade) >> 152) & type(uint88).max); (cashAmount, fCashAmount) = market.removeLiquidity(tokens); tokens = tokens.neg(); // Report a negative amount tokens in the event } { uint256 minImpliedRate = uint32(uint256(trade) >> 120); uint256 maxImpliedRate = uint32(uint256(trade) >> 88); // If minImpliedRate is not set then it will be zero require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage"); if (maxImpliedRate != 0) require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage"); } // Add the assets in this order so they are sorted portfolioState.addAsset( cashGroup.currencyId, market.maturity, Constants.FCASH_ASSET_TYPE, fCashAmount ); // Adds the liquidity token asset portfolioState.addAsset( cashGroup.currencyId, market.maturity, marketIndex + 1, tokens ); emit AddRemoveLiquidity( account, cashGroup.currencyId, // This will not overflow for a long time uint40(market.maturity), cashAmount, fCashAmount, tokens ); return cashAmount; } /// @notice Executes a lend or borrow trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param tradeType whether this is add or remove liquidity /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return cashAmount - a positive or negative cash amount accrued to the account /// @return fCashAmount - a positive or negative fCash amount accrued to the account function _executeLendBorrowTrade( CashGroupParameters memory cashGroup, MarketParameters memory market, TradeActionType tradeType, uint256 blockTime, bytes32 trade ) private returns ( int256 cashAmount, int256 fCashAmount ) { uint256 marketIndex = uint256(uint8(bytes1(trade << 8))); // NOTE: this updates the market in memory cashGroup.loadMarket(market, marketIndex, false, blockTime); fCashAmount = int256(uint88(bytes11(trade << 16))); // fCash to account will be negative here if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg(); cashAmount = market.executeTrade( cashGroup, fCashAmount, market.maturity.sub(blockTime), marketIndex ); require(cashAmount != 0, "Trade failed, liquidity"); uint256 rateLimit = uint256(uint32(bytes4(trade << 104))); if (rateLimit != 0) { if (tradeType == TradeActionType.Borrow) { // Do not allow borrows over the rate limit require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage"); } else { // Do not allow lends under the rate limit require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage"); } } } /// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty /// rate to the 3 month market. /// @param account the account initiating the trade, used to check that self settlement is not possible /// @param cashGroup parameters for the trade /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return maturity: the date of the three month maturity where fCash will be exchanged /// @return cashAmount: a negative cash amount that the account must pay to the settled account /// @return fCashAmount: a positive fCash amount that the account will receive function _settleCashDebt( address account, CashGroupParameters memory cashGroup, uint256 blockTime, bytes32 trade ) internal returns ( uint256, int256, int256 ) { address counterparty = address(uint256(trade) >> 88); // Allowing an account to settle itself would result in strange outcomes require(account != counterparty, "Cannot settle self"); int256 amountToSettleAsset = int256(uint88(uint256(trade))); AccountContext memory counterpartyContext = AccountContextHandler.getAccountContext(counterparty); if (counterpartyContext.mustSettleAssets()) { counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext); } // This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive // number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the // max amount to settle. This will update the balance storage on the counterparty. amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt( counterparty, cashGroup, amountToSettleAsset, counterpartyContext ); // Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market // is not initialized. uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; int256 fCashAmount = _getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset); // Defensive check to ensure that we can't inadvertently cause the settler to lose fCash. require(fCashAmount >= 0); // It's possible that this action will put an account into negative free collateral. In this case they // will immediately become eligible for liquidation and the account settling the debt can also liquidate // them in the same transaction. Do not run a free collateral check here to allow this to happen. { PortfolioAsset[] memory assets = new PortfolioAsset[](1); assets[0].currencyId = cashGroup.currencyId; assets[0].maturity = threeMonthMaturity; assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur assets[0].assetType = Constants.FCASH_ASSET_TYPE; // Can transfer assets, we have settled above counterpartyContext = TransferAssets.placeAssetsInAccount( counterparty, counterpartyContext, assets ); } counterpartyContext.setAccountContext(counterparty); emit SettledCashDebt( counterparty, uint16(cashGroup.currencyId), account, amountToSettleAsset, fCashAmount.neg() ); return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount); } /// @dev Helper method to calculate the fCashAmount from the penalty settlement rate function _getfCashSettleAmount( CashGroupParameters memory cashGroup, uint256 threeMonthMaturity, uint256 blockTime, int256 amountToSettleAsset ) private view returns (int256) { uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime); int256 exchangeRate = Market.getExchangeRateFromImpliedRate( oracleRate.add(cashGroup.getSettlementPenalty()), threeMonthMaturity.sub(blockTime) ); // Amount to settle is positive, this returns the fCashAmount that the settler will // receive as a positive number return cashGroup.assetRate .convertToUnderlying(amountToSettleAsset) // Exchange rate converts from cash to fCash when multiplying .mulInRatePrecision(exchangeRate); } /// @notice Allows an account to purchase ntoken residuals /// @param purchaser account that is purchasing the residuals /// @param cashGroup parameters for the trade /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged /// @return cashAmount: a positive or negative cash amount that the account will receive or pay /// @return fCashAmount: a positive or negative fCash amount that the account will receive function _purchaseNTokenResidual( address purchaser, CashGroupParameters memory cashGroup, uint256 blockTime, bytes32 trade ) internal returns ( uint256, int256, int256 ) { uint256 maturity = uint256(uint32(uint256(trade) >> 216)); int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128)); require(maturity > blockTime, "Invalid maturity"); // Require that the residual to purchase does not fall on an existing maturity (i.e. // it is an idiosyncratic maturity) require( !DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime), "Non idiosyncratic maturity" ); address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, /* assetArrayLength */, bytes5 parameters ) = nTokenHandler.getNTokenContext(nTokenAddress); // Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage // opportunities are not available (by generating residuals and then immediately purchasing them at a discount) // This is always relative to the last initialized time which is set at utc0 when initialized, not the // reference time. Therefore we will always restrict residual purchase relative to initialization, not reference. // This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization // until the residual time buffer passes. require( blockTime > lastInitializedTime.add( uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours ), "Insufficient block time" ); int256 notional = BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity); // Check if amounts are valid and set them to the max available if necessary if (notional < 0 && fCashAmountToPurchase < 0) { // Does not allow purchasing more negative notional than available if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional; } else if (notional > 0 && fCashAmountToPurchase > 0) { // Does not allow purchasing more positive notional than available if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional; } else { // Does not allow moving notional in the opposite direction revert("Invalid amount"); } // If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return // netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken. int256 netAssetCashNToken = _getResidualPriceAssetCash( cashGroup, maturity, blockTime, fCashAmountToPurchase, parameters ); _updateNTokenPortfolio( nTokenAddress, cashGroup.currencyId, maturity, lastInitializedTime, fCashAmountToPurchase, netAssetCashNToken ); emit nTokenResidualPurchase( uint16(cashGroup.currencyId), uint40(maturity), purchaser, fCashAmountToPurchase, netAssetCashNToken ); return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase); } /// @notice Returns the amount of asset cash required to purchase the nToken residual function _getResidualPriceAssetCash( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime, int256 fCashAmount, bytes6 parameters ) internal view returns (int256) { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); // Residual purchase incentive is specified in ten basis point increments uint256 purchaseIncentive = uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) * Constants.TEN_BASIS_POINTS; if (fCashAmount > 0) { // When fCash is positive then we add the purchase incentive, the purchaser // can pay less cash for the fCash relative to the oracle rate oracleRate = oracleRate.add(purchaseIncentive); } else if (oracleRate > purchaseIncentive) { // When fCash is negative, we reduce the interest rate that the purchaser will // borrow at, we do this check to ensure that we floor the oracle rate at zero. oracleRate = oracleRate.sub(purchaseIncentive); } else { // If the oracle rate is less than the purchase incentive floor the interest rate at zero oracleRate = 0; } int256 exchangeRate = Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime)); // Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount return cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate)); } function _updateNTokenPortfolio( address nTokenAddress, uint256 currencyId, uint256 maturity, uint256 lastInitializedTime, int256 fCashAmountToPurchase, int256 netAssetCashNToken ) private { int256 finalNotional = BitmapAssetsHandler.addifCashAsset( nTokenAddress, currencyId, maturity, lastInitializedTime, fCashAmountToPurchase.neg() // the nToken takes on the negative position ); // Defensive check to ensure that fCash amounts do not flip signs require( (fCashAmountToPurchase > 0 && finalNotional >= 0) || (fCashAmountToPurchase < 0 && finalNotional <= 0) ); // prettier-ignore ( int256 nTokenCashBalance, /* storedNTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId); nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken); // This will ensure that the cash balance is not negative BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/StorageLayoutV1.sol"; import "../../internal/nToken/nTokenHandler.sol"; abstract contract ActionGuards is StorageLayoutV1 { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; function initializeReentrancyGuard() internal { require(reentrancyStatus == 0); // Initialize the guard to a non-zero value, see the OZ reentrancy guard // description for why this is more gas efficient: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol reentrancyStatus = _NOT_ENTERED; } modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(reentrancyStatus != _ENTERED, "Reentrant call"); // Any calls to nonReentrant after this point will fail reentrancyStatus = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) reentrancyStatus = _NOT_ENTERED; } // These accounts cannot receive deposits, transfers, fCash or any other // types of value transfers. function requireValidAccount(address account) internal view { require(account != Constants.RESERVE); // Reserve address is address(0) require(account != address(this)); ( uint256 isNToken, /* incentiveAnnualEmissionRate */, /* lastInitializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(account); require(isNToken == 0); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenMintAction { using SafeInt256 for int256; using BalanceHandler for BalanceState; using CashGroup for CashGroupParameters; using Market for MarketParameters; using nTokenHandler for nTokenPortfolio; using PortfolioHandler for PortfolioState; using AssetRate for AssetRateParameters; using SafeMath for uint256; using nTokenHandler for nTokenPortfolio; /// @notice Converts the given amount of cash to nTokens in the same currency. /// @param currencyId the currency associated the nToken /// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals /// @return nTokens minted by this action function nTokenMint(uint16 currencyId, int256 amountToDepositInternal) external returns (int256) { uint256 blockTime = block.timestamp; nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime); require(tokensToMint >= 0, "Invalid token amount"); if (nToken.portfolioState.storedAssets.length == 0) { // If the token does not have any assets, then the markets must be initialized first. nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, currencyId, nToken.cashBalance ); } else { _depositIntoPortfolio(nToken, amountToDepositInternal, blockTime); } // NOTE: token supply does not change here, it will change after incentives have been claimed // during BalanceHandler.finalize return tokensToMint; } /// @notice Calculates the tokens to mint to the account as a ratio of the nToken /// present value denominated in asset cash terms. /// @return the amount of tokens to mint, the ifCash bitmap function calculateTokensToMint( nTokenPortfolio memory nToken, int256 amountToDepositInternal, uint256 blockTime ) internal view returns (int256) { require(amountToDepositInternal >= 0); // dev: deposit amount negative if (amountToDepositInternal == 0) return 0; if (nToken.lastInitializedTime != 0) { // For the sake of simplicity, nTokens cannot be minted if they have assets // that need to be settled. This is only done during market initialization. uint256 nextSettleTime = nToken.getNextSettleTime(); // If next settle time <= blockTime then the token can be settled require(nextSettleTime > blockTime, "Requires settlement"); } int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // Defensive check to ensure PV remains positive require(assetCashPV >= 0); // Allow for the first deposit if (nToken.totalSupply == 0) { return amountToDepositInternal; } else { // assetCashPVPost = assetCashPV + amountToDeposit // (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV // (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV // (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV // tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV); } } /// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When /// entering this method we know that assetCashDeposit is positive and the nToken has been /// initialized to have liquidity tokens. function _depositIntoPortfolio( nTokenPortfolio memory nToken, int256 assetCashDeposit, uint256 blockTime ) private { (int256[] memory depositShares, int256[] memory leverageThresholds) = nTokenHandler.getDepositParameters( nToken.cashGroup.currencyId, nToken.cashGroup.maxMarketIndex ); // Loop backwards from the last market to the first market, the reasoning is a little complicated: // If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient // to calculate the cash amount to lend. We do know that longer term maturities will have more // slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get // closer to the current block time. Any residual cash from lending will be rolled into shorter // markets as this loop progresses. int256 residualCash; MarketParameters memory market; for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) { int256 fCashAmount; // Loads values into the market memory slot nToken.cashGroup.loadMarket( market, marketIndex, true, // Needs liquidity to true blockTime ); // If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex // before initializing if (market.totalLiquidity == 0) continue; // Checked that assetCashDeposit must be positive before entering int256 perMarketDeposit = assetCashDeposit .mul(depositShares[marketIndex - 1]) .div(Constants.DEPOSIT_PERCENT_BASIS) .add(residualCash); (fCashAmount, residualCash) = _lendOrAddLiquidity( nToken, market, perMarketDeposit, leverageThresholds[marketIndex - 1], marketIndex, blockTime ); if (fCashAmount != 0) { BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, nToken.cashGroup.currencyId, market.maturity, nToken.lastInitializedTime, fCashAmount ); } } // nToken is allowed to store assets directly without updating account context. nToken.portfolioState.storeAssets(nToken.tokenAddress); // Defensive check to ensure that we do not somehow accrue negative residual cash. require(residualCash >= 0, "Negative residual cash"); // This will occur if the three month market is over levered and we cannot lend into it if (residualCash > 0) { // Any remaining residual cash will be put into the nToken balance and added as liquidity on the // next market initialization nToken.cashBalance = nToken.cashBalance.add(residualCash); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.cashBalance ); } } /// @notice For a given amount of cash to deposit, decides how much to lend or provide /// given the market conditions. function _lendOrAddLiquidity( nTokenPortfolio memory nToken, MarketParameters memory market, int256 perMarketDeposit, int256 leverageThreshold, uint256 marketIndex, uint256 blockTime ) private returns (int256 fCashAmount, int256 residualCash) { // We start off with the entire per market deposit as residuals residualCash = perMarketDeposit; // If the market is over leveraged then we will lend to it instead of providing liquidity if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { (residualCash, fCashAmount) = _deleverageMarket( nToken.cashGroup, market, perMarketDeposit, blockTime, marketIndex ); // Recalculate this after lending into the market, if it is still over leveraged then // we will not add liquidity and just exit. if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { // Returns the residual cash amount return (fCashAmount, residualCash); } } // Add liquidity to the market only if we have successfully delevered. // (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored // If deleveraged, residualCash is what remains // If not deleveraged, residual cash is per market deposit fCashAmount = fCashAmount.add( _addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash) ); // No residual cash if we're adding liquidity return (fCashAmount, 0); } /// @notice Markets are over levered when their proportion is greater than a governance set /// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken /// account for the given amount of cash deposited, putting the nToken account at risk of liquidation. /// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead. function _isMarketOverLeveraged( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 leverageThreshold ) private pure returns (bool) { int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // Comparison we want to do: // (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold // However, the division will introduce rounding errors so we change this to: // totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying) // Leverage threshold is denominated in rate precision. return ( market.totalfCash.mul(Constants.RATE_PRECISION) > leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying)) ); } function _addLiquidityToMarket( nTokenPortfolio memory nToken, MarketParameters memory market, uint256 index, int256 perMarketDeposit ) private returns (int256) { // Add liquidity to the market PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index]; // We expect that all the liquidity tokens are in the portfolio in order. require( asset.maturity == market.maturity && // Ensures that the asset type references the proper liquidity token asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX && // Ensures that the storage state will not be overwritten asset.storageState == AssetStorageState.NoChange, "PT: invalid liquidity token" ); // This will update the market state as well, fCashAmount returned here is negative (int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit); asset.notional = asset.notional.add(liquidityTokens); asset.storageState = AssetStorageState.Update; return fCashAmount; } /// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due /// to slippage or result in some amount of residual cash. function _deleverageMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 perMarketDeposit, uint256 blockTime, uint256 marketIndex ) private returns (int256, int256) { uint256 timeToMaturity = market.maturity.sub(blockTime); // Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this // is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here // because it is very gas inefficient. int256 assumedExchangeRate; if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) { // Floor the exchange rate at zero interest rate assumedExchangeRate = Constants.RATE_PRECISION; } else { assumedExchangeRate = Market.getExchangeRateFromImpliedRate( market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER), timeToMaturity ); } int256 fCashAmount; { int256 perMarketDepositUnderlying = cashGroup.assetRate.convertToUnderlying(perMarketDeposit); // NOTE: cash * exchangeRate = fCash fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate); } int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex); // This means that the trade failed if (netAssetCash == 0) { return (perMarketDeposit, 0); } else { // Ensure that net the per market deposit figure does not drop below zero, this should not be possible // given how we've calculated the exchange rate but extra caution here int256 residual = perMarketDeposit.add(netAssetCash); require(residual >= 0); // dev: insufficient cash return (residual, fCashAmount); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../internal/markets/Market.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/portfolio/TransferAssets.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenRedeemAction { using SafeInt256 for int256; using SafeMath for uint256; using Bitmap for bytes32; using BalanceHandler for BalanceState; using Market for MarketParameters; using CashGroup for CashGroupParameters; using PortfolioHandler for PortfolioState; using nTokenHandler for nTokenPortfolio; /// @notice When redeeming nTokens via the batch they must all be sold to cash and this /// method will return the amount of asset cash sold. /// @param currencyId the currency associated the nToken /// @param tokensToRedeem the amount of nTokens to convert to cash /// @return amount of asset cash to return to the account, denominated in internal token decimals function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem) external returns (int256) { uint256 blockTime = block.timestamp; // prettier-ignore ( int256 totalAssetCash, bool hasResidual, /* PortfolioAssets[] memory newfCashAssets */ ) = _redeem(currencyId, tokensToRedeem, true, false, blockTime); require(!hasResidual, "Cannot redeem via batch, residual"); return totalAssetCash; } /// @notice Redeems nTokens for asset cash and fCash /// @param currencyId the currency associated the nToken /// @param tokensToRedeem the amount of nTokens to convert to cash /// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place /// back into the account's portfolio /// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will /// be no penalty assessed /// @return assetCash positive amount of asset cash to the account /// @return hasResidual true if there are fCash residuals left /// @return assets an array of fCash asset residuals to place into the account function redeem( uint16 currencyId, int256 tokensToRedeem, bool sellTokenAssets, bool acceptResidualAssets ) external returns (int256, bool, PortfolioAsset[] memory) { return _redeem( currencyId, tokensToRedeem, sellTokenAssets, acceptResidualAssets, block.timestamp ); } function _redeem( uint16 currencyId, int256 tokensToRedeem, bool sellTokenAssets, bool acceptResidualAssets, uint256 blockTime ) internal returns (int256, bool, PortfolioAsset[] memory) { require(tokensToRedeem > 0); nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); // nTokens cannot be redeemed during the period of time where they require settlement. require(nToken.getNextSettleTime() > blockTime, "Requires settlement"); require(tokensToRedeem < nToken.totalSupply, "Cannot redeem"); PortfolioAsset[] memory newifCashAssets; // Get the ifCash bits that are idiosyncratic bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits( nToken.tokenAddress, currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); if (ifCashBits != 0 && acceptResidualAssets) { // This will remove all the ifCash assets proportionally from the account newifCashAssets = _reduceifCashAssetsProportional( nToken.tokenAddress, currencyId, nToken.lastInitializedTime, tokensToRedeem, nToken.totalSupply, ifCashBits ); // Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw // simply gets the proportional amount of liquidity tokens to remove ifCashBits = 0; } // Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only // set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens (int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw( nToken, tokensToRedeem, blockTime, ifCashBits ); // Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated // in memory if required and will contain the fCash to be sold or returned to the portfolio int256 totalAssetCash = _reduceLiquidAssets( nToken, tokensToRedeem, tokensToWithdraw, netfCash, ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts blockTime ); bool netfCashRemaining = true; if (sellTokenAssets) { int256 assetCash; // NOTE: netfCash is modified in place and set to zero if the fCash is sold (assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime); totalAssetCash = totalAssetCash.add(assetCash); } if (netfCashRemaining) { // If the account is unwilling to accept residuals then will fail here. require(acceptResidualAssets, "Residuals"); newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash); } return (totalAssetCash, netfCashRemaining, newifCashAssets); } /// @notice Removes liquidity tokens and cash from the nToken /// @param nToken portfolio object /// @param nTokensToRedeem tokens to redeem /// @param tokensToWithdraw array of liquidity tokens to withdraw /// @param netfCash array of netfCash figures /// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step /// @param blockTime current block time /// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken function _reduceLiquidAssets( nTokenPortfolio memory nToken, int256 nTokensToRedeem, int256[] memory tokensToWithdraw, int256[] memory netfCash, bool mustCalculatefCash, uint256 blockTime ) private returns (int256 assetCashShare) { // Get asset cash share for the nToken, if it exists. It is required in balance handler that the // nToken can never have a negative cash asset cash balance so what we get here is always positive // or zero. assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply); if (assetCashShare > 0) { nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.cashBalance ); } // Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash // is set to true assetCashShare = assetCashShare.add( _removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash) ); nToken.portfolioState.storeAssets(nToken.tokenAddress); // NOTE: Token supply change will happen when we finalize balances and after minting of incentives return assetCashShare; } /// @notice Removes nToken liquidity tokens and updates the netfCash figures. /// @param nToken portfolio object /// @param nTokensToRedeem tokens to redeem /// @param tokensToWithdraw array of liquidity tokens to withdraw /// @param netfCash array of netfCash figures /// @param blockTime current block time /// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step /// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims function _removeLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem, int256[] memory tokensToWithdraw, int256[] memory netfCash, uint256 blockTime, bool mustCalculatefCash ) private returns (int256 totalAssetCashClaims) { MarketParameters memory market; for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i]; asset.notional = asset.notional.sub(tokensToWithdraw[i]); // Cannot redeem liquidity tokens down to zero or this will cause many issues with // market initialization. require(asset.notional > 0, "Cannot redeem to zero"); require(asset.storageState == AssetStorageState.NoChange); asset.storageState = AssetStorageState.Update; // This will load a market object in memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); int256 fCashClaim; { int256 assetCash; // Remove liquidity from the market (assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]); totalAssetCashClaims = totalAssetCashClaims.add(assetCash); } int256 fCashToNToken; if (mustCalculatefCash) { // Do this calculation if net ifCash is not set, will happen if there are no residuals int256 fCashShare = BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, asset.maturity ); fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply); // netfCash = fCashClaim + fCashShare netfCash[i] = fCashClaim.add(fCashShare); fCashToNToken = fCashShare.neg(); } else { // Account will receive netfCash amount. Deduct that from the fCash claim and add the // remaining back to the nToken to net off the nToken's position // fCashToNToken = -fCashShare // netfCash = fCashClaim + fCashShare // fCashToNToken = -(netfCash - fCashClaim) // fCashToNToken = fCashClaim - netfCash fCashToNToken = fCashClaim.sub(netfCash[i]); } // Removes the account's fCash position from the nToken BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, asset.currencyId, asset.maturity, nToken.lastInitializedTime, fCashToNToken ); } return totalAssetCashClaims; } /// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash /// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on /// fCash assets. function _sellfCashAssets( nTokenPortfolio memory nToken, int256[] memory netfCash, uint256 blockTime ) private returns (int256 totalAssetCash, bool hasResidual) { MarketParameters memory market; hasResidual = false; for (uint256 i = 0; i < netfCash.length; i++) { if (netfCash[i] == 0) continue; nToken.cashGroup.loadMarket(market, i + 1, false, blockTime); int256 netAssetCash = market.executeTrade( nToken.cashGroup, // Use the negative of fCash notional here since we want to net it out netfCash[i].neg(), nToken.portfolioState.storedAssets[i].maturity.sub(blockTime), i + 1 ); if (netAssetCash == 0) { // This means that the trade failed hasResidual = true; } else { totalAssetCash = totalAssetCash.add(netAssetCash); netfCash[i] = 0; } } } /// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array function _addResidualsToAssets( PortfolioAsset[] memory liquidityTokens, PortfolioAsset[] memory newifCashAssets, int256[] memory netfCash ) internal pure returns (PortfolioAsset[] memory finalfCashAssets) { uint256 numAssetsToExtend; for (uint256 i = 0; i < netfCash.length; i++) { if (netfCash[i] != 0) numAssetsToExtend++; } uint256 newLength = newifCashAssets.length + numAssetsToExtend; finalfCashAssets = new PortfolioAsset[](newLength); uint index = 0; for (; index < newifCashAssets.length; index++) { finalfCashAssets[index] = newifCashAssets[index]; } uint netfCashIndex = 0; for (; index < finalfCashAssets.length; ) { if (netfCash[netfCashIndex] != 0) { PortfolioAsset memory asset = finalfCashAssets[index]; asset.currencyId = liquidityTokens[netfCashIndex].currencyId; asset.maturity = liquidityTokens[netfCashIndex].maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = netfCash[netfCashIndex]; index++; } netfCashIndex++; } return finalfCashAssets; } /// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming /// nTokens to its underlying assets. function _reduceifCashAssetsProportional( address account, uint256 currencyId, uint256 lastInitializedTime, int256 tokensToRedeem, int256 totalSupply, bytes32 assetsBitmap ) internal returns (PortfolioAsset[] memory) { uint256 index = assetsBitmap.totalBitsSet(); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; int256 notional = fCashSlot.notional; int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply); int256 finalNotional = notional.sub(notionalToTransfer); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notionalToTransfer; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../internal/portfolio/PortfolioHandler.sol"; import "../internal/balances/BalanceHandler.sol"; import "../internal/settlement/SettlePortfolioAssets.sol"; import "../internal/settlement/SettleBitmapAssets.sol"; import "../internal/AccountContextHandler.sol"; /// @notice External library for settling assets library SettleAssetsExternal { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; event AccountSettled(address indexed account); /// @notice Settles an account, returns the new account context object after settlement. /// @dev The memory location of the account context object is not the same as the one returned. function settleAccount( address account, AccountContext memory accountContext ) external returns (AccountContext memory) { // Defensive check to ensure that this is a valid settlement require(accountContext.mustSettleAssets()); SettleAmount[] memory settleAmounts; PortfolioState memory portfolioState; if (accountContext.isBitmapEnabled()) { (int256 settledCash, uint256 blockTimeUTC0) = SettleBitmapAssets.settleBitmappedCashGroup( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, block.timestamp ); require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow accountContext.nextSettleTime = uint40(blockTimeUTC0); settleAmounts = new SettleAmount[](1); settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash); } else { portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp); accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts); emit AccountSettled(account); return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../external/SettleAssetsExternal.sol"; import "../internal/AccountContextHandler.sol"; import "../internal/valuation/FreeCollateral.sol"; /// @title Externally deployed library for free collateral calculations library FreeCollateralExternal { using AccountContextHandler for AccountContext; /// @notice Returns the ETH denominated free collateral of an account, represents the amount of /// debt that the account can incur before liquidation. If an account's assets need to be settled this /// will revert, either settle the account or use the off chain SDK to calculate free collateral. /// @dev Called via the Views.sol method to return an account's free collateral. Does not work /// for the nToken, the nToken does not have an account context. /// @param account account to calculate free collateral for /// @return total free collateral in ETH w/ 8 decimal places /// @return array of net local values in asset values ordered by currency id function getFreeCollateralView(address account) external view returns (int256, int256[] memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); // The internal free collateral function does not account for settled assets. The Notional SDK // can calculate the free collateral off chain if required at this point. require(!accountContext.mustSettleAssets(), "Assets not settled"); return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp); } /// @notice Calculates free collateral and will revert if it falls below zero. If the account context /// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets /// need to be settled first. /// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be /// called before the end of any transaction for accounts where FC can decrease. /// @param account account to calculate free collateral for function checkFreeCollateralAndRevert(address account) external { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); require(!accountContext.mustSettleAssets(), "Assets not settled"); (int256 ethDenominatedFC, bool updateContext) = FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp); if (updateContext) { accountContext.setAccountContext(account); } require(ethDenominatedFC >= 0, "Insufficient free collateral"); } /// @notice Calculates liquidation factors for an account /// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is /// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then /// liquidation actions will revert. /// @dev an ntoken account will return 0 FC and revert if called /// @param account account to liquidate /// @param localCurrencyId currency that the debts are denominated in /// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation /// @return accountContext the accountContext of the liquidated account /// @return factors struct of relevant factors for liquidation /// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array) function getLiquidationFactors( address account, uint256 localCurrencyId, uint256 collateralCurrencyId ) external returns ( AccountContext memory accountContext, LiquidationFactors memory factors, PortfolioAsset[] memory portfolio ) { accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { accountContext = SettleAssetsExternal.settleAccount(account, accountContext); } if (accountContext.isBitmapEnabled()) { // A bitmap currency can only ever hold debt in this currency require(localCurrencyId == accountContext.bitmapCurrencyId); } (factors, portfolio) = FreeCollateral.getLiquidationFactors( account, accountContext, block.timestamp, localCurrencyId, collateralCurrencyId ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../global/Constants.sol"; library SafeInt256 { int256 private constant _INT256_MIN = type(int256).min; /// @dev Returns the multiplication of two signed integers, reverting on /// overflow. /// Counterpart to Solidity's `*` operator. /// Requirements: /// - Multiplication cannot overflow. function mul(int256 a, int256 b) internal pure returns (int256 c) { c = a * b; if (a == -1) require (b == 0 || c / b == a); else require (a == 0 || c / a == b); } /// @dev Returns the integer division of two signed integers. Reverts on /// division by zero. The result is rounded towards zero. /// Counterpart to Solidity's `/` operator. Note: this function uses a /// `revert` opcode (which leaves remaining gas untouched) while Solidity /// uses an invalid opcode to revert (consuming all remaining gas). /// Requirements: /// - The divisor cannot be zero. function div(int256 a, int256 b) internal pure returns (int256 c) { require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow // NOTE: solidity will automatically revert on divide by zero c = a / b; } function sub(int256 x, int256 y) internal pure returns (int256 z) { // taken from uniswap v3 require((z = x - y) <= x == (y >= 0)); } function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } function neg(int256 x) internal pure returns (int256 y) { return mul(-1, x); } function abs(int256 x) internal pure returns (int256) { if (x < 0) return neg(x); else return x; } function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) { z = sub(x, y); require(z >= 0); // dev: int256 sub to negative return z; } /// @dev Calculates x * RATE_PRECISION / y while checking overflows function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, Constants.RATE_PRECISION), y); } /// @dev Calculates x * y / RATE_PRECISION while checking overflows function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, y), Constants.RATE_PRECISION); } function toUint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function toInt(uint256 x) internal pure returns (int256) { require (x <= uint256(type(int256).max)); // dev: toInt overflow return int256(x); } function max(int256 x, int256 y) internal pure returns (int256) { return x > y ? x : y; } function min(int256 x, int256 y) internal pure returns (int256) { return x < y ? x : y; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; /** * @notice Storage layout for the system. Do not change this file once deployed, future storage * layouts must inherit this and increment the version number. */ contract StorageLayoutV1 { // The current maximum currency id uint16 internal maxCurrencyId; // Sets the state of liquidations being enabled during a paused state. Each of the four lower // bits can be turned on to represent one of the liquidation types being enabled. bytes1 internal liquidationEnabledState; // Set to true once the system has been initialized bool internal hasInitialized; /* Authentication Mappings */ // This is set to the timelock contract to execute governance functions address public owner; // This is set to an address of a router that can only call governance actions address public pauseRouter; // This is set to an address of a router that can only call governance actions address public pauseGuardian; // On upgrades this is set in the case that the pause router is used to pass the rollback check address internal rollbackRouterImplementation; // A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user // to set an allowance on all nTokens for a particular integrating contract system. // owner => spender => transferAllowance mapping(address => mapping(address => uint256)) internal nTokenWhitelist; // Individual transfer allowances for nTokens used for ERC20 // owner => spender => currencyId => transferAllowance mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance; // Transfer operators // Mapping from a global ERC1155 transfer operator contract to an approval value for it mapping(address => bool) internal globalTransferOperator; // Mapping from an account => operator => approval status for that operator. This is a specific // approval between two addresses for ERC1155 transfers. mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator; // Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in // BatchAction.sol, can only be set by governance mapping(address => bool) internal authorizedCallbackContract; // Reverse mapping from token addresses to currency ids, only used for referencing in views // and checking for duplicate token listings. mapping(address => uint16) internal tokenAddressToCurrencyId; // Reentrancy guard uint256 internal reentrancyStatus; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Incentives.sol"; import "./TokenHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/FloatingPoint56.sol"; library BalanceHandler { using SafeInt256 for int256; using TokenHandler for Token; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; /// @notice Emitted when a cash balance changes event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); /// @notice Emitted when nToken supply changes (not the same as transfers) event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Emitted when reserve balance is updated event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance); /// @notice Emitted when reserve balance is harvested event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount); /// @notice Deposits asset tokens into an account /// @dev Handles two special cases when depositing tokens into an account. /// - If a token has transfer fees then the amount specified does not equal the amount that the contract /// will receive. Complete the deposit here rather than in finalize so that the contract has the correct /// balance to work with. /// - Force a transfer before finalize to allow a different account to deposit into an account /// @return assetAmountInternal which is the converted asset amount accounting for transfer fees function depositAssetToken( BalanceState memory balanceState, address account, int256 assetAmountExternal, bool forceTransfer ) internal returns (int256 assetAmountInternal) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); // dev: deposit asset token amount negative Token memory token = TokenHandler.getAssetToken(balanceState.currencyId); if (token.tokenType == TokenType.aToken) { // Handles special accounting requirements for aTokens assetAmountExternal = AaveHandler.convertToScaledBalanceExternal( balanceState.currencyId, assetAmountExternal ); } // Force transfer is used to complete the transfer before going to finalize if (token.hasTransferFee || forceTransfer) { // If the token has a transfer fee the deposit amount may not equal the actual amount // that the contract will receive. We handle the deposit here and then update the netCashChange // accordingly which is denominated in internal precision. int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal); // Convert the external precision to internal, it's possible that we lose dust amounts here but // this is unavoidable because we do not know how transfer fees are calculated. assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal); // Transfer has been called balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal); return assetAmountInternal; } else { assetAmountInternal = token.convertToInternal(assetAmountExternal); // Otherwise add the asset amount here. It may be net off later and we want to only do // a single transfer during the finalize method. Use internal precision to ensure that internal accounting // and external account remain in sync. // Transfer will be deferred balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .add(assetAmountInternal); // Returns the converted assetAmountExternal to the internal amount return assetAmountInternal; } } /// @notice Handle deposits of the underlying token /// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up /// with any underlying tokens left as dust on the contract. function depositUnderlyingToken( BalanceState memory balanceState, address account, int256 underlyingAmountExternal ) internal returns (int256) { if (underlyingAmountExternal == 0) return 0; require(underlyingAmountExternal > 0); // dev: deposit underlying token negative Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // This is the exact amount of underlying tokens the account has in external precision. if (underlyingToken.tokenType == TokenType.Ether) { // Underflow checked above require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance"); } else { underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal); } Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); int256 assetTokensReceivedExternalPrecision = assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal)); // cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different // type of asset token is listed in the future. It's possible if those tokens have a different precision dust may // accrue but that is not relevant now. int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision); // Transfer / mint has taken effect balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal); return assetTokensReceivedInternal; } /// @notice Finalizes an account's balances, handling any transfer logic required /// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken /// as the nToken is limited in what types of balances it can hold. function finalize( BalanceState memory balanceState, address account, AccountContext memory accountContext, bool redeemToUnderlying ) internal returns (int256 transferAmountExternal) { bool mustUpdate; if (balanceState.netNTokenTransfer < 0) { require( balanceState.storedNTokenBalance .add(balanceState.netNTokenSupplyChange) .add(balanceState.netNTokenTransfer) >= 0, "Neg nToken" ); } if (balanceState.netAssetTransferInternalPrecision < 0) { require( balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= 0, "Neg Cash" ); } // Transfer amount is checked inside finalize transfers in case when converting to external we // round down to zero. This returns the actual net transfer in internal precision as well. ( transferAmountExternal, balanceState.netAssetTransferInternalPrecision ) = _finalizeTransfers(balanceState, account, redeemToUnderlying); // No changes to total cash after this point int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange ); } if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) { // Final nToken balance is used to calculate the account incentive debt int256 finalNTokenBalance = balanceState.storedNTokenBalance .add(balanceState.netNTokenTransfer) .add(balanceState.netNTokenSupplyChange); // The toUint() call here will ensure that nToken balances never become negative Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint()); balanceState.storedNTokenBalance = finalNTokenBalance; if (balanceState.netNTokenSupplyChange != 0) { emit nTokenSupplyChange( account, uint16(balanceState.currencyId), balanceState.netNTokenSupplyChange ); } mustUpdate = true; } if (mustUpdate) { _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } accountContext.setActiveCurrency( balanceState.currencyId, // Set active currency to true if either balance is non-zero balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (balanceState.storedCashBalance < 0) { // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances // are examined accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } } /// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying /// is specified. function _finalizeTransfers( BalanceState memory balanceState, address account, bool redeemToUnderlying ) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) { Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Dust accrual to the protocol is possible if the token decimals is less than internal token precision. // See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal int256 assetTransferAmountExternal = assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision); if (assetTransferAmountExternal == 0) { return (0, 0); } else if (redeemToUnderlying && assetTransferAmountExternal < 0) { // We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than // zero then we will do a normal transfer instead. // We use the internal amount here and then scale it to the external amount so that there is // no loss of precision between our internal accounting and the external account. In this case // there will be no dust accrual in underlying tokens since we will transfer the exact amount // of underlying that was received. actualTransferAmountExternal = assetToken.redeem( balanceState.currencyId, account, // No overflow, checked above uint256(assetTransferAmountExternal.neg()) ); // In this case we're transferring underlying tokens, we want to convert the internal // asset transfer amount to store in cash balances assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal); } else { // NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it // will be converted to balanceOf denomination inside transfer actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal); // Convert the actual transferred amount assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal); } } /// @notice Special method for settling negative current cash debts. This occurs when an account /// has a negative fCash balance settle to cash. A settler may come and force the account to borrow /// at the prevailing 3 month rate /// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary. function setBalanceStorageForSettleCashDebt( address account, CashGroupParameters memory cashGroup, int256 amountToSettleAsset, AccountContext memory accountContext ) internal returns (int256) { require(amountToSettleAsset >= 0); // dev: amount to settle negative (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, cashGroup.currencyId); // Prevents settlement of positive balances require(cashBalance < 0, "Invalid settle balance"); if (amountToSettleAsset == 0) { // Symbolizes that the entire debt should be settled amountToSettleAsset = cashBalance.neg(); cashBalance = 0; } else { // A partial settlement of the debt require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle"); cashBalance = cashBalance.add(amountToSettleAsset); } // NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances // also have cash debts if (cashBalance == 0 && nTokenBalance == 0) { accountContext.setActiveCurrency( cashGroup.currencyId, false, Constants.ACTIVE_IN_BALANCES ); } _setBalanceStorage( account, cashGroup.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); // Emit the event here, we do not call finalize emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset); return amountToSettleAsset; } /** * @notice A special balance storage method for fCash liquidation to reduce the bytecode size. */ function setBalanceStorageForfCashLiquidation( address account, AccountContext memory accountContext, uint16 currencyId, int256 netCashChange ) internal { (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, currencyId); int256 newCashBalance = cashBalance.add(netCashChange); // If a cash balance is negative already we cannot put an account further into debt. In this case // the netCashChange must be positive so that it is coming out of debt. if (newCashBalance < 0) { require(netCashChange > 0, "Neg Cash"); // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check // where all balances are examined. In this case the has cash debt flag should // already be set (cash balances cannot get more negative) but we do it again // here just to be safe. accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } bool isActive = newCashBalance != 0 || nTokenBalance != 0; accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES); // Emit the event here, we do not call finalize emit CashBalanceChange(account, currencyId, netCashChange); _setBalanceStorage( account, currencyId, newCashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } /// @notice Helper method for settling the output of the SettleAssets method function finalizeSettleAmounts( address account, AccountContext memory accountContext, SettleAmount[] memory settleAmounts ) internal { for (uint256 i = 0; i < settleAmounts.length; i++) { SettleAmount memory amt = settleAmounts[i]; if (amt.netCashChange == 0) continue; ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) = getBalanceStorage(account, amt.currencyId); cashBalance = cashBalance.add(amt.netCashChange); accountContext.setActiveCurrency( amt.currencyId, cashBalance != 0 || nTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (cashBalance < 0) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } emit CashBalanceChange( account, uint16(amt.currencyId), amt.netCashChange ); _setBalanceStorage( account, amt.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } } /// @notice Special method for setting balance storage for nToken function setBalanceStorageForNToken( address nTokenAddress, uint256 currencyId, int256 cashBalance ) internal { require(cashBalance >= 0); // dev: invalid nToken cash balance _setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0); } /// @notice increments fees to the reserve function incrementFeeToReserve(uint256 currencyId, int256 fee) internal { require(fee >= 0); // dev: invalid fee // prettier-ignore (int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId); totalReserve = totalReserve.add(fee); _setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0); emit ReserveFeeAccrued(uint16(currencyId), fee); } /// @notice harvests excess reserve balance function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal { // parameters are validated by the caller reserve = reserve.subNoNeg(assetInternalRedeemAmount); _setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0); emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount); } /// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal { require(newBalance >= 0); // dev: invalid balance _setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0); emit ReserveBalanceUpdated(currencyId, newBalance); } /// @notice Sets internal balance storage. function _setBalanceStorage( address account, uint256 currencyId, int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) private { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow // Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow if (lastClaimTime == 0) { // In this case the account has migrated and we set the accountIncentiveDebt // The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never // encounter an overflow for accountIncentiveDebt require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt); } else { // In this case the last claim time has not changed and we do not update the last integral supply // (stored in the accountIncentiveDebt position) require(lastClaimTime == balanceStorage.lastClaimTime); } balanceStorage.lastClaimTime = uint32(lastClaimTime); balanceStorage.nTokenBalance = uint80(nTokenBalance); balanceStorage.cashBalance = int88(cashBalance); } /// @notice Gets internal balance storage, nTokens are stored alongside cash balances function getBalanceStorage(address account, uint256 currencyId) internal view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; nTokenBalance = balanceStorage.nTokenBalance; lastClaimTime = balanceStorage.lastClaimTime; if (lastClaimTime > 0) { // NOTE: this is only necessary to support the deprecated integral supply values, which are stored // in the accountIncentiveDebt slot accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt); } else { accountIncentiveDebt = balanceStorage.accountIncentiveDebt; } cashBalance = balanceStorage.cashBalance; } /// @notice Loads a balance state memory object /// @dev Balance state objects occupy a lot of memory slots, so this method allows /// us to reuse them if possible function loadBalanceState( BalanceState memory balanceState, address account, uint16 currencyId, AccountContext memory accountContext ) internal view { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id balanceState.currencyId = currencyId; if (accountContext.isActiveInBalances(currencyId)) { ( balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ) = getBalanceStorage(account, currencyId); } else { balanceState.storedCashBalance = 0; balanceState.storedNTokenBalance = 0; balanceState.lastClaimTime = 0; balanceState.accountIncentiveDebt = 0; } balanceState.netCashChange = 0; balanceState.netAssetTransferInternalPrecision = 0; balanceState.netNTokenTransfer = 0; balanceState.netNTokenSupplyChange = 0; } /// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state /// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts /// are migrated to the new incentive calculation function claimIncentivesManual(BalanceState memory balanceState, address account) internal returns (uint256 incentivesClaimed) { incentivesClaimed = Incentives.claimIncentives( balanceState, account, balanceState.storedNTokenBalance.toUint() ); _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TransferAssets.sol"; import "../valuation/AssetHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; /// @notice Handles the management of an array of assets including reading from storage, inserting /// updating, deleting and writing back to storage. library PortfolioHandler { using SafeInt256 for int256; using AssetHandler for PortfolioAsset; // Mirror of LibStorage.MAX_PORTFOLIO_ASSETS uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @notice Primarily used by the TransferAssets library function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets) internal pure { for (uint256 i = 0; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; addAsset( portfolioState, asset.currencyId, asset.maturity, asset.assetType, asset.notional ); } } function _mergeAssetIntoArray( PortfolioAsset[] memory assetArray, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) private pure returns (bool) { for (uint256 i = 0; i < assetArray.length; i++) { PortfolioAsset memory asset = assetArray[i]; if ( asset.assetType != assetType || asset.currencyId != currencyId || asset.maturity != maturity ) continue; // Either of these storage states mean that some error in logic has occurred, we cannot // store this portfolio require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: portfolio handler deleted storage int256 newNotional = asset.notional.add(notional); // Liquidity tokens cannot be reduced below zero. if (AssetHandler.isLiquidityToken(assetType)) { require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance } require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow asset.notional = newNotional; asset.storageState = AssetStorageState.Update; return true; } return false; } /// @notice Adds an asset to a portfolio state in memory (does not write to storage) /// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity /// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional. function addAsset( PortfolioState memory portfolioState, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) internal pure { if ( // Will return true if merged _mergeAssetIntoArray( portfolioState.storedAssets, currencyId, maturity, assetType, notional ) ) return; if (portfolioState.lastNewAssetIndex > 0) { bool merged = _mergeAssetIntoArray( portfolioState.newAssets, currencyId, maturity, assetType, notional ); if (merged) return; } // At this point if we have not merged the asset then append to the array // Cannot remove liquidity that the portfolio does not have if (AssetHandler.isLiquidityToken(assetType)) { require(notional >= 0); // dev: portfolio handler negative liquidity token balance } require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow // Need to provision a new array at this point if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) { portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets); } // Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will // check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct. PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex]; newAsset.currencyId = currencyId; newAsset.maturity = maturity; newAsset.assetType = assetType; newAsset.notional = notional; newAsset.storageState = AssetStorageState.NoChange; portfolioState.lastNewAssetIndex += 1; } /// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do /// it too much function _extendNewAssetArray(PortfolioAsset[] memory newAssets) private pure returns (PortfolioAsset[] memory) { // Double the size of the new asset array every time we have to extend to reduce the number of times // that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there). uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2; PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength); for (uint256 i = 0; i < newAssets.length; i++) { extendedArray[i] = newAssets[i]; } return extendedArray; } /// @notice Takes a portfolio state and writes it to storage. /// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via /// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library. /// @return updated variables to update the account context with /// hasDebt: whether or not the portfolio has negative fCash assets /// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio /// uint8: the length of the storage array /// uint40: the new nextSettleTime for the portfolio function storeAssets(PortfolioState memory portfolioState, address account) internal returns ( bool, bytes32, uint8, uint40 ) { bool hasDebt; // NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is // set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate // 7 additional fCash assets for a total of 14 assets. Although even in this case all assets // would be of the same currency so it would not change the end result of the active currency // calculation. bytes32 portfolioActiveCurrencies; uint256 nextSettleTime; for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler // during valuation. require(asset.storageState != AssetStorageState.RevertIfStored); // Mark any zero notional assets as deleted if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) { deleteAsset(portfolioState, i); } } // First delete assets from asset storage to maintain asset storage indexes for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; if (asset.storageState == AssetStorageState.Delete) { // Delete asset from storage uint256 currentSlot = asset.storageSlot; assembly { sstore(currentSlot, 0x00) } } else { if (asset.storageState == AssetStorageState.Update) { PortfolioAssetStorage storage assetStorage; uint256 currentSlot = asset.storageSlot; assembly { assetStorage.slot := currentSlot } _storeAsset(asset, assetStorage); } // Update portfolio context for every asset that is in storage, whether it is // updated in storage or not. (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); } } // Add new assets uint256 assetStorageLength = portfolioState.storedAssetLength; mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; for (uint256 i = 0; i < portfolioState.newAssets.length; i++) { PortfolioAsset memory asset = portfolioState.newAssets[i]; if (asset.notional == 0) continue; require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: store assets deleted storage (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); _storeAsset(asset, storageArray[assetStorageLength]); assetStorageLength += 1; } // 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with // 2 bytes per currency require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow return ( hasDebt, portfolioActiveCurrencies, uint8(assetStorageLength), uint40(nextSettleTime) ); } /// @notice Updates context information during the store assets method function _updatePortfolioContext( PortfolioAsset memory asset, bool hasDebt, bytes32 portfolioActiveCurrencies, uint256 nextSettleTime ) private pure returns ( bool, bytes32, uint256 ) { uint256 settlementDate = asset.getSettlementDate(); // Tis will set it to the minimum settlement date if (nextSettleTime == 0 || nextSettleTime > settlementDate) { nextSettleTime = settlementDate; } hasDebt = hasDebt || asset.notional < 0; require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240); return (hasDebt, portfolioActiveCurrencies, nextSettleTime); } /// @dev Encodes assets for storage function _storeAsset( PortfolioAsset memory asset, PortfolioAssetStorage storage assetStorage ) internal { require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow assetStorage.currencyId = uint16(asset.currencyId); assetStorage.maturity = uint40(asset.maturity); assetStorage.assetType = uint8(asset.assetType); assetStorage.notional = int88(asset.notional); } /// @notice Deletes an asset from a portfolio /// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement /// by adding the offsetting negative position function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure { require(index < portfolioState.storedAssets.length); // dev: stored assets bounds require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index]; require( assetToDelete.storageState != AssetStorageState.Delete && assetToDelete.storageState != AssetStorageState.RevertIfStored ); // dev: cannot delete asset portfolioState.storedAssetLength -= 1; uint256 maxActiveSlotIndex; uint256 maxActiveSlot; // The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the // array so we search for it here. for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory a = portfolioState.storedAssets[i]; if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) { maxActiveSlot = a.storageSlot; maxActiveSlotIndex = i; } } if (index == maxActiveSlotIndex) { // In this case we are deleting the asset with the max storage slot so no swap is necessary. assetToDelete.storageState = AssetStorageState.Delete; return; } // Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly // so that when we call store assets they will be updated appropriately PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex]; ( assetToSwap.storageSlot, assetToDelete.storageSlot ) = ( assetToDelete.storageSlot, assetToSwap.storageSlot ); assetToSwap.storageState = AssetStorageState.Update; assetToDelete.storageState = AssetStorageState.Delete; } /// @notice Returns a portfolio array, will be sorted function getSortedPortfolio(address account, uint8 assetArrayLength) internal view returns (PortfolioAsset[] memory) { PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength); // No sorting required for length of 1 if (assets.length <= 1) return assets; _sortInPlace(assets); return assets; } /// @notice Builds a portfolio array from storage. The new assets hint parameter will /// be used to provision a new array for the new assets. This will increase gas efficiency /// so that we don't have to make copies when we extend the array. function buildPortfolioState( address account, uint8 assetArrayLength, uint256 newAssetsHint ) internal view returns (PortfolioState memory) { PortfolioState memory state; if (assetArrayLength == 0) return state; state.storedAssets = getSortedPortfolio(account, assetArrayLength); state.storedAssetLength = assetArrayLength; state.newAssets = new PortfolioAsset[](newAssetsHint); return state; } function _sortInPlace(PortfolioAsset[] memory assets) private pure { uint256 length = assets.length; uint256[] memory ids = new uint256[](length); for (uint256 k; k < length; k++) { PortfolioAsset memory asset = assets[k]; // Prepopulate the ids to calculate just once ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType); } // Uses insertion sort uint256 i = 1; while (i < length) { uint256 j = i; while (j > 0 && ids[j - 1] > ids[j]) { // Swap j - 1 and j (ids[j - 1], ids[j]) = (ids[j], ids[j - 1]); (assets[j - 1], assets[j]) = (assets[j], assets[j - 1]); j--; } i++; } } function _loadAssetArray(address account, uint8 length) private view returns (PortfolioAsset[] memory) { // This will overflow the storage pointer require(length <= MAX_PORTFOLIO_ASSETS); mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; PortfolioAsset[] memory assets = new PortfolioAsset[](length); for (uint256 i = 0; i < length; i++) { PortfolioAssetStorage storage assetStorage = storageArray[i]; PortfolioAsset memory asset = assets[i]; uint256 slot; assembly { slot := assetStorage.slot } asset.currencyId = assetStorage.currencyId; asset.maturity = assetStorage.maturity; asset.assetType = assetStorage.assetType; asset.notional = assetStorage.notional; asset.storageSlot = slot; } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./balances/BalanceHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; library AccountContextHandler { using PortfolioHandler for PortfolioState; bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF; event AccountContextUpdate(address indexed account); /// @notice Returns the account context of a given account function getAccountContext(address account) internal view returns (AccountContext memory) { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); return store[account]; } /// @notice Sets the account context of a given account function setAccountContext(AccountContext memory accountContext, address account) internal { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); store[account] = accountContext; emit AccountContextUpdate(account); } function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) { return accountContext.bitmapCurrencyId != 0; } /// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows /// an account to hold more fCash than a normal portfolio, except only in a single currency. /// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if /// it has no assets or debt so that we ensure no assets are left stranded. /// @param accountContext refers to the account where the bitmap will be enabled /// @param currencyId the id of the currency to enable /// @param blockTime the current block time to set the next settle time function enableBitmapForAccount( AccountContext memory accountContext, uint16 currencyId, uint256 blockTime ) internal view { require(!isBitmapEnabled(accountContext), "Cannot change bitmap"); require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id"); // Account cannot have assets or debts require(accountContext.assetArrayLength == 0, "Cannot have assets"); require(accountContext.hasDebt == 0x00, "Cannot have debt"); // Ensure that the active currency is set to false in the array so that there is no double // counting during FreeCollateral setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES); accountContext.bitmapCurrencyId = currencyId; // Setting this is required to initialize the assets bitmap uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime); require(nextSettleTime < type(uint40).max); // dev: blockTime overflow accountContext.nextSettleTime = uint40(nextSettleTime); } /// @notice Returns true if the context needs to settle function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) { uint256 blockTime = block.timestamp; if (isBitmapEnabled(accountContext)) { // nextSettleTime will be set to utc0 after settlement so we // settle if this is strictly less than utc0 return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime); } else { // 0 value occurs on an uninitialized account // Assets mature exactly on the blockTime (not one second past) so in this // case we settle on the block timestamp return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime; } } /// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account /// context active currencies list. /// @dev NOTE: this may be more efficient as a binary search since we know that the array /// is sorted function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId) internal pure returns (bool) { require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id bytes18 currencies = accountContext.activeCurrencies; if (accountContext.bitmapCurrencyId == currencyId) return true; while (currencies != 0x00) { uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (cid == currencyId) { // Currency found, return if it is active in balances or not return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES; } currencies = currencies << 16; } return false; } /// @notice Iterates through the active currency list and removes, inserts or does nothing /// to ensure that the active currency list is an ordered byte array of uint16 currency ids /// that refer to the currencies that an account is active in. /// /// This is called to ensure that currencies are active when the account has a non zero cash balance, /// a non zero nToken balance or a portfolio asset. function setActiveCurrency( AccountContext memory accountContext, uint256 currencyId, bool isActive, bytes2 flags ) internal pure { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id // If the bitmapped currency is already set then return here. Turning off the bitmap currency // id requires other logical handling so we will do it elsewhere. if (isActive && accountContext.bitmapCurrencyId == currencyId) return; bytes18 prefix; bytes18 suffix = accountContext.activeCurrencies; uint256 shifts; /// There are six possible outcomes from this search: /// 1. The currency id is in the list /// - it must be set to active, do nothing /// - it must be set to inactive, shift suffix and concatenate /// 2. The current id is greater than the one in the search: /// - it must be set to active, append to prefix and then concatenate the suffix, /// ensure that we do not lose the last 2 bytes if set. /// - it must be set to inactive, it is not in the list, do nothing /// 3. Reached the end of the list: /// - it must be set to active, check that the last two bytes are not set and then /// append to the prefix /// - it must be set to inactive, do nothing while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS)); // if matches and isActive then return, already in list if (cid == currencyId && isActive) { // set flag and return accountContext.activeCurrencies = accountContext.activeCurrencies | (bytes18(flags) >> (shifts * 16)); return; } // if matches and not active then shift suffix to remove if (cid == currencyId && !isActive) { // turn off flag, if both flags are off then remove suffix = suffix & ~bytes18(flags); if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16; accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16)); return; } // if greater than and isActive then insert into prefix if (cid > currencyId && isActive) { prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); // check that the total length is not greater than 9, meaning that the last // two bytes of the active currencies array should be zero require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies // append the suffix accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16)); return; } // if past the point of the currency id and not active, not in list if (cid > currencyId && !isActive) return; prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16)); suffix = suffix << 16; shifts += 1; } // If reached this point and not active then return if (!isActive) return; // if end and isActive then insert into suffix, check max length require(shifts < 9); // dev: AC: too many currencies accountContext.activeCurrencies = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); } function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) { bytes18 result; // This is required to clear the suffix as we append below bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS; uint256 shifts; // This loop will append all currencies that are active in balances into the result. while (suffix != 0x00) { if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { // If any flags are active, then append. result = result | (bytes18(bytes2(suffix)) >> shifts); shifts += 16; } suffix = suffix << 16; } return result; } /// @notice Stores a portfolio array and updates the account context information, this method should /// be used whenever updating a portfolio array except in the case of nTokens function storeAssetsAndUpdateContext( AccountContext memory accountContext, address account, PortfolioState memory portfolioState, bool isLiquidation ) internal { // Each of these parameters is recalculated based on the entire array of assets in store assets, // regardless of whether or not they have been updated. (bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) = portfolioState.storeAssets(account); accountContext.nextSettleTime = nextSettleTime; require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets accountContext.assetArrayLength = assetArrayLength; // During liquidation it is possible for an array to go over the max amount of assets allowed due to // liquidity tokens being withdrawn into fCash. if (!isLiquidation) { require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed } // Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning // a negative fCash balance. if (hasDebt) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } else { // Turns off the ASSET_DEBT flag accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; } // Clear the active portfolio active flags and they will be recalculated in the next step accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) { // Portfolio currencies will not have flags, it is just an byte array of all the currencies found // in a portfolio. They are appended in a sorted order so we can compare to the previous currency // and only set it if they are different. uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); } lastCurrency = currencyId; portfolioCurrencies = portfolioCurrencies << 16; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; interface NotionalCallback { function notionalCallback(address sender, address account, bytes calldata callbackdata) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetRate.sol"; import "./CashGroup.sol"; import "./DateTime.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; // Max positive value for a ABDK64x64 integer int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; /// @notice Add liquidity to a market, assuming that it is initialized. If not then /// this method will revert and the market must be initialized first. /// Return liquidityTokens and negative fCash to the portfolio function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); require(assetCash > 0); // dev: negative asset cash liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); // No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion. fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); // Flip the sign to represent the LP's net position fCash = fCash.neg(); } /// @notice Remove liquidity from a market, assuming that it is initialized. /// Return assetCash and positive fCash to the portfolio function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); require(tokensToRemove > 0); // dev: negative tokens to remove assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } /// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive /// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory. /// @param market the current market state /// @param cashGroup cash group configuration parameters /// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change /// to the market is in the opposite direction. /// @param timeToMaturity number of seconds until maturity /// @return netAssetCash, netAssetCashToReserve function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { // We return false if there is not enough fCash to support this trade. // if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail // if fCashToAccount < 0 and totalfCash > 0 then this will always pass if (market.totalfCash <= fCashToAccount) return (0, 0); // Calculates initial rate factors for the trade (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); // Calculates the exchange rate from cash to fCash before any liquidity fees // are applied int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } // Given the exchange rate, returns the net cash amounts to apply to each of the // three relevant balances. (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); // Signifies a failed net cash amount calculation if (netCashToAccount == 0) return (0, 0); { // Set the new implied interest rate after the trade has taken effect, this // will be used to calculate the next trader's interest rate. market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); // It's technically possible that the implied rate is actually exactly zero (or // more accurately the natural log rounds down to zero) but we will still fail // in this case. If this does happen we may assume that markets are not initialized. if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } /// @notice Returns factors for calculating exchange rates /// @return /// rateScalar: a scalar value in rate precision that defines the slope of the line /// totalCashUnderlying: the converted asset cash to underlying cash for calculating /// the exchange rates for the trade /// rateAnchor: an offset from the x axis to maintain interest rate continuity over time function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // This would result in a divide by zero if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); // Get the rate anchor given the market state, this will establish the baseline for where // the exchange rate is set. int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } /// @dev Returns net asset cash amounts to the account, the market and the reserve /// @return /// netCashToAccount: this is a positive or negative amount of cash change to the account /// netCashToMarket: this is a positive or negative amount of cash change in the market // netCashToReserve: this is always a positive amount of cash accrued to the reserve function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { // Fees are specified in basis points which is an rate precision denomination. We convert this to // an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply // or divide depending on the side of the trade). // tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity) // tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity) // cash = fCash / exchangeRate, exchangeRate > 1 int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { // Lending // Dividing reduces exchange rate, lending should receive less fCash for cash int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); // It's possible that the fee pushes exchange rates into negative territory. This is not possible // when borrowing. If this happens then the trade has failed. if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate // preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate) // postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate) // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1) // netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1) // netFee = preFeeCashToAccount * (1 - feeExchangeRate) // RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0 fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); } else { // Borrowing // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1) // netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate) // NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number // preFee * (1 - fee) / fee will be negative, use neg() to flip to positive // RATE_PRECISION - fee will be negative fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( // postFeeCashToAccount = preFeeCashToAccount - fee preFeeCashToAccount.sub(fee), // netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve) (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), cashToReserve ); } /// @notice Sets the new market state /// @return /// netAssetCashToAccount: the positive or negative change in asset cash to the account /// assetCashToReserve: the positive amount of cash that accrues to the reserve function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); // Set storage checks that total asset cash is above zero market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); // Sets the trade time for the next oracle update market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } /// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable /// across time or markets but implied rates are. The goal here is to ensure that the implied rate /// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied /// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage /// which will hurt the liquidity providers. /// /// The rate anchor will update as the market rolls down to maturity. The calculation is: /// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME) /// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar /// /// where: /// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity') /// (calculated when the last trade in the market was made) /// @return the new rate anchor and a boolean that signifies success function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { // This is the exchange rate at the new time to maturity int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { // totalfCash / (totalfCash + totalCashUnderlying) int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } /// @notice Calculates the current market implied rate. /// @return the implied rate and a bool that is true on success function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { // This will check for exchange rates < Constants.RATE_PRECISION (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; // Uses continuous compounding to calculate the implied rate: // ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity int128 rate = ABDKMath64x64.fromInt(exchangeRate); // Scales down to a floating point for LN int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); // We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION // inside getExchangeRate int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); // Scales up to a fixed point uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); // lnRate * IMPLIED_RATE_TIME / ttm uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); // Implied rates over 429% will overflow, this seems like a safe assumption if (impliedRate > type(uint32).max) return 0; return impliedRate; } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// formula is E = e^rt function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } /// @notice Returns the exchange rate between fCash and cash for the given market /// Calculates the following exchange rate: /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalfCash / (totalfCash + totalUnderlyingCash) /// @dev has an underscore to denote as private but is marked internal for the mock function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); // This is the proportion scaled by Constants.RATE_PRECISION // (totalfCash + fCash) / (totalfCash + totalCashUnderlying) int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); // This limit is here to prevent the market from reaching extremely high interest rates via an // excessively large proportion (high amounts of fCash relative to cash). // Market proportion can only increase via borrowing (fCash is added to the market and cash is // removed). Over time, the returns from asset cash will slightly decrease the proportion (the // value of cash underlying in the market must be monotonically increasing). Therefore it is not // possible for the proportion to go over max market proportion unless borrowing occurs. if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // lnProportion / rateScalar + rateAnchor int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); // Do not succeed if interest rates fall below 1 if (rate < Constants.RATE_PRECISION) { return (0, false); } else { return (rate, true); } } /// @dev This method calculates the log of the proportion inside the logit function which is /// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with /// fixed point precision and the ABDK library. function _logProportion(int256 proportion) internal pure returns (int256, bool) { // This will result in divide by zero, short circuit if (proportion == Constants.RATE_PRECISION) return (0, false); // Convert proportion to what is used inside the logit function (p / (1-p)) int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); // ABDK does not handle log of numbers that are less than 1, in order to get the right value // scaled by RATE_PRECISION we use the log identity: // (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION int128 abdkProportion = ABDKMath64x64.fromInt(logitP); // Here, abdk will revert due to negative log so abort if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } /// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value /// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example, /// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates. /// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then /// be liquidated. /// /// Oracle rates are calculated when the market is loaded from storage. /// /// The oracle rate is a lagged weighted average over a short term price window. If we are past /// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the /// weighted average: /// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow + /// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow) function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero // This can occur when using a view function get to a market state in the past if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { // If past the time window just return the lastImpliedRate return lastImpliedRate; } // (currentTs - previousTs) / timeWindow uint256 lastTradeWeight = timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); // 1 - (currentTs - previousTs) / timeWindow uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; // If the oracle rate is set to zero this can only be because the markets have past their settlement // date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated // during this time, but market initialization can be called by anyone so the actual time that this condition // exists for should be quite short. require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } /// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method /// which ensures that the rate oracle is set properly. function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { // Market object always uses the most current reference time as the settlement date mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; } else { market.totalLiquidity = 0; } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); // Oracle rate does not change on liquidity uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { // On initialization we have not yet calculated the storage slot so we get it here. mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately. function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this /// is mainly used in the InitializeMarketAction contract. function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } /// Uses Newton's method to converge on an fCash amount given the amount of /// cash. The relation between cash and fcash is: /// cashAmount * exchangeRate * fee + fCash = 0 /// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor /// p = (totalfCash - fCash) / (totalfCash + totalCash) /// if cashAmount < 0: fee = feeRate ^ -1 /// if cashAmount > 0: fee = feeRate /// /// Newton's method is: /// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash) /// /// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash /// /// (totalfCash + totalCash) /// exchangeRate'(fCash) = - ------------------------------------------ /// (totalfCash - fCash) * (totalCash + fCash) /// /// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29 /// /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) /// /// NOTE: each iteration costs about 11.3k so this is only done via a view function. function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); require(success); // dev: invalid exchange rate int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } /// @dev Calculates: f(fCash) / f'(fCash) /// f(fCash) = cashAmount * exchangeRate * fee + fCash /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; // rateScalar * (totalfCash - fCash) * (totalCash + fCash) // Precision: TOKEN_PRECISION ^ 2 int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { // Lending exchangeRate = exchangeRate.divInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount / fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); } else { // Borrowing exchangeRate = exchangeRate.mulInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount * fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } // 1 - numerator / denominator // Precision: TOKEN_PRECISION derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); // f(fCash) = cashAmount * exchangeRate * fee + fCash // NOTE: exchangeRate at this point already has the fee taken into account int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); numerator = numerator.add(fCashGuess); // f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION // here instead of RATE_PRECISION return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Market.sol"; import "./AssetRate.sol"; import "./DateTime.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library CashGroup { using SafeMath for uint256; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; // Bit number references for each parameter in the 32 byte word (0-indexed) uint256 private constant MARKET_INDEX_BIT = 31; uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30; uint256 private constant TOTAL_FEE_BIT = 29; uint256 private constant RESERVE_FEE_SHARE_BIT = 28; uint256 private constant DEBT_BUFFER_BIT = 27; uint256 private constant FCASH_HAIRCUT_BIT = 26; uint256 private constant SETTLEMENT_PENALTY_BIT = 25; uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24; uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23; // 7 bytes allocated, one byte per market for the liquidity token haircut uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22; // 7 bytes allocated, one byte per market for the rate scalar uint256 private constant RATE_SCALAR_FIRST_BIT = 15; // Offsets for the bytes of the different parameters uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8; uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8; uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8; uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8; uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8; uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8; uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8; uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8; uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8; uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8; uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8; /// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies /// the ln() portion of the liquidity curve as an inverse so it increases with time to /// maturity. The effect of the rate scalar on slippage must decrease with time to maturity. function getRateScalar( CashGroupParameters memory cashGroup, uint256 marketIndex, uint256 timeToMaturity ) internal pure returns (int256) { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1); int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION; int256 rateScalar = scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity)); // Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the // division above. require(rateScalar > 0); // dev: rate scalar underflow return rateScalar; } /// @notice Haircut on liquidity tokens to account for the risk associated with changes in the /// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100. function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType) internal pure returns (uint8) { require( Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX ); // dev: liquidity haircut invalid asset type uint256 offset = LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX); return uint8(uint256(cashGroup.data >> offset)); } /// @notice Total trading fee denominated in RATE_PRECISION with basis point increments function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT; } /// @notice Percentage of the total trading fee that goes to the reserve function getReserveFeeShare(CashGroupParameters memory cashGroup) internal pure returns (int256) { return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE)); } /// @notice fCash haircut for valuation denominated in rate precision with five basis point increments function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } /// @notice Time window factor for the rate oracle denominated in seconds with five minute increments. function getRateOracleTimeWindow(CashGroupParameters memory cashGroup) internal pure returns (uint256) { // This is denominated in 5 minute increments in storage return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES; } /// @notice Penalty rate for settling cash debts denominated in basis points function getSettlementPenalty(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for positive fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for negative fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } function loadMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 marketIndex, bool needsLiquidity, uint256 blockTime ) internal view { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market"); uint256 maturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex)); market.loadMarket( cashGroup.currencyId, maturity, blockTime, needsLiquidity, getRateOracleTimeWindow(cashGroup) ); } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity ) internal pure returns (uint256) { require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) // NOTE: this subtraction should never overflow, the linear interpolation between two points above zero // cannot go below zero return shortRate.sub( // This is reversed to keep it it positive (shortRate - longRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) ); } } /// @dev Gets an oracle rate given any valid maturity. function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); } else { uint256 referenceTime = DateTime.getReferenceTime(blockTime); // DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { // In this case the short market is the annualized asset supply rate shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); } else { // Minimum value for marketIndex here is 2 shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } } function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) { mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); return store[currencyId]; } /// @dev Helper method for validating maturities in ERC1155Action function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) { bytes32 data = _getCashGroupStorageBytes(currencyId); return uint8(data[MARKET_INDEX_BIT]); } /// @notice Checks all cash group settings for invalid values and sets them into storage function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal { // Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market. // The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month // fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash // groups with 0 market index, it has no effect. require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: invalid market index" ); require( cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS, "CG: invalid reserve share" ); require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex); require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex); // This is required so that fCash liquidation can proceed correctly require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS); require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS); // Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId); require( previousMaxMarketIndex <= cashGroup.maxMarketIndex, "CG: market index cannot decrease" ); // Per cash group settings bytes32 data = (bytes32(uint256(cashGroup.maxMarketIndex)) | (bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) | (bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) | (bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) | (bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) | (bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) | (bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) << LIQUIDATION_FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER)); // Per market group settings for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) { require( cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS, "CG: invalid token haircut" ); data = data | (bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) << (LIQUIDITY_TOKEN_HAIRCUT + i * 8)); } for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) { // Causes a divide by zero error require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar"); data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8)); } mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); store[currencyId] = data; } /// @notice Deserialize the cash group storage bytes into a user friendly object function deserializeCashGroupStorage(uint256 currencyId) internal view returns (CashGroupSettings memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex)); uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex)); for (uint8 i = 0; i < maxMarketIndex; i++) { tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]); rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]); } return CashGroupSettings({ maxMarketIndex: maxMarketIndex, rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]), totalFeeBPS: uint8(data[TOTAL_FEE_BIT]), reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]), debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]), fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]), settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]), liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]), liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]), liquidityTokenHaircuts: tokenHaircuts, rateScalars: rateScalars }); } function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate) private view returns (CashGroupParameters memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); return CashGroupParameters({ currencyId: currencyId, maxMarketIndex: maxMarketIndex, assetRate: assetRate, data: data }); } /// @notice Builds a cash group using a view version of the asset rate function buildCashGroupView(uint16 currencyId) internal view returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId); return _buildCashGroup(currencyId, assetRate); } /// @notice Builds a cash group using a stateful version of the asset rate function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId); return _buildCashGroup(currencyId, assetRate); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/notional/AssetRateAdapter.sol"; library AssetRate { using SafeInt256 for int256; event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); // Asset rates are in 1e18 decimals (cToken exchange rates), internal balances // are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10 int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10; /// @notice Converts an internal asset cash value to its underlying token value. /// @param ar exchange rate object between asset and underlying /// @param assetBalance amount to convert to underlying function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256) { // Calculation here represents: // rate * balance * internalPrecision / rateDecimals * underlyingPrecision int256 underlyingBalance = ar.rate .mul(assetBalance) .div(ASSET_RATE_DECIMAL_DIFFERENCE) .div(ar.underlyingDecimals); return underlyingBalance; } /// @notice Converts an internal underlying cash value to its asset cash value /// @param ar exchange rate object between asset and underlying /// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance) internal pure returns (int256) { // Calculation here represents: // rateDecimals * balance * underlyingPrecision / rate * internalPrecision int256 assetBalance = underlyingBalance .mul(ASSET_RATE_DECIMAL_DIFFERENCE) .mul(ar.underlyingDecimals) .div(ar.rate); return assetBalance; } /// @notice Returns the current per block supply rate, is used when calculating oracle rates /// for idiosyncratic fCash with a shorter duration than the 3 month maturity. function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) { // If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero. if (address(ar.rateOracle) == address(0)) return 0; uint256 rate = ar.rateOracle.getAnnualizedSupplyRate(); // Zero supply rate is valid since this is an interest rate, we do not divide by // the supply rate so we do not get div by zero errors. require(rate >= 0); // dev: invalid supply rate return rate; } function _getAssetRateStorage(uint256 currencyId) private view returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) { mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); AssetRateStorage storage ar = store[currencyId]; rateOracle = AssetRateAdapter(ar.rateOracle); underlyingDecimalPlaces = ar.underlyingDecimalPlaces; } /// @notice Gets an asset rate using a view function, does not accrue interest so the /// exchange rate will not be up to date. Should only be used for non-stateful methods function _getAssetRateView(uint256 currencyId) private view returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateView(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Gets an asset rate using a stateful function, accrues interest so the /// exchange rate will be up to date for the current block. function _getAssetRateStateful(uint256 currencyId) private returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateStateful(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Returns an asset rate object using the view method function buildAssetRateView(uint256 currencyId) internal view returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateView(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @notice Returns an asset rate object using the stateful method function buildAssetRateStateful(uint256 currencyId) internal returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStateful(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @dev Gets a settlement rate object function _getSettlementRateStorage(uint256 currencyId, uint256 maturity) private view returns ( int256 settlementRate, uint8 underlyingDecimalPlaces ) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); SettlementRateStorage storage rateStorage = store[currencyId][maturity]; settlementRate = rateStorage.settlementRate; underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces; } /// @notice Returns a settlement rate object using the view method function buildSettlementRateView(uint256 currencyId, uint256 maturity) internal view returns (AssetRateParameters memory) { // prettier-ignore ( int256 settlementRate, uint8 underlyingDecimalPlaces ) = _getSettlementRateStorage(currencyId, maturity); // Asset exchange rates cannot be zero if (settlementRate == 0) { // If settlement rate has not been set then we need to fetch it // prettier-ignore ( settlementRate, /* address */, underlyingDecimalPlaces ) = _getAssetRateView(currencyId); } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } /// @notice Returns a settlement rate object and sets the rate if it has not been set yet function buildSettlementRateStateful( uint256 currencyId, uint256 maturity, uint256 blockTime ) internal returns (AssetRateParameters memory) { (int256 settlementRate, uint8 underlyingDecimalPlaces) = _getSettlementRateStorage(currencyId, maturity); if (settlementRate == 0) { // Settlement rate has not yet been set, set it in this branch AssetRateAdapter rateOracle; // If rate oracle == 0 then this will return the identity settlement rate // prettier-ignore ( settlementRate, rateOracle, underlyingDecimalPlaces ) = _getAssetRateStateful(currencyId); if (address(rateOracle) != address(0)) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); // Only need to set settlement rates when the rate oracle is set (meaning the asset token has // a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1 // rate since they are the same. require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow SettlementRateStorage storage rateStorage = store[currencyId][maturity]; rateStorage.blockTime = uint40(blockTime); rateStorage.settlementRate = uint128(settlementRate); rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces; emit SetSettlementRate(currencyId, maturity, uint128(settlementRate)); } } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./PortfolioHandler.sol"; import "./BitmapAssetsHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../math/SafeInt256.sol"; /// @notice Helper library for transferring assets from one portfolio to another library TransferAssets { using AccountContextHandler for AccountContext; using PortfolioHandler for PortfolioState; using SafeInt256 for int256; /// @notice Decodes asset ids function decodeAssetId(uint256 id) internal pure returns ( uint256 currencyId, uint256 maturity, uint256 assetType ) { assetType = uint8(id); maturity = uint40(id >> 8); currencyId = uint16(id >> 48); } /// @notice Encodes asset ids function encodeAssetId( uint256 currencyId, uint256 maturity, uint256 assetType ) internal pure returns (uint256) { require(currencyId <= Constants.MAX_CURRENCIES); require(maturity <= type(uint40).max); require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); return uint256( (bytes32(uint256(uint16(currencyId))) << 48) | (bytes32(uint256(uint40(maturity))) << 8) | bytes32(uint256(uint8(assetType))) ); } /// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure { for (uint256 i; i < assets.length; i++) { assets[i].notional = assets[i].notional.neg(); } } /// @dev Useful method for hiding the logic of updating an account. WARNING: the account /// context returned from this method may not be the same memory location as the account /// context provided if the account is settled. function placeAssetsInAccount( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal returns (AccountContext memory) { // If an account has assets that require settlement then placing assets inside it // may cause issues. require(!accountContext.mustSettleAssets(), "Account must settle"); if (accountContext.isBitmapEnabled()) { // Adds fCash assets into the account and finalized storage BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets); } else { PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, assets.length ); // This will add assets in memory portfolioState.addMultipleAssets(assets); // This will store assets and update the account context in memory accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } return accountContext; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetHandler.sol"; import "./ExchangeRate.sol"; import "../markets/CashGroup.sol"; import "../AccountContextHandler.sol"; import "../balances/BalanceHandler.sol"; import "../portfolio/PortfolioHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenCalculations.sol"; import "../../math/SafeInt256.sol"; library FreeCollateral { using SafeInt256 for int256; using Bitmap for bytes; using ExchangeRate for ETHRate; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; using nTokenHandler for nTokenPortfolio; /// @dev This is only used within the library to clean up the stack struct FreeCollateralFactors { int256 netETHValue; bool updateContext; uint256 portfolioIndex; CashGroupParameters cashGroup; MarketParameters market; PortfolioAsset[] portfolio; AssetRateParameters assetRate; nTokenPortfolio nToken; } /// @notice Checks if an asset is active in the portfolio function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) { return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO; } /// @notice Checks if currency balances are active in the account returns them if true /// @return cash balance, nTokenBalance function _getCurrencyBalances(address account, bytes2 currencyBytes) private view returns (int256, int256) { if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // prettier-ignore ( int256 cashBalance, int256 nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, currencyId); return (cashBalance, nTokenBalance); } return (0, 0); } /// @notice Calculates the nToken asset value with a haircut set by governance /// @return the value of the account's nTokens after haircut, the nToken parameters function _getNTokenHaircutAssetPV( CashGroupParameters memory cashGroup, nTokenPortfolio memory nToken, int256 tokenBalance, uint256 blockTime ) internal view returns (int256, bytes6) { nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId); nToken.cashGroup = cashGroup; int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // (tokenBalance * nTokenValue * haircut) / totalSupply int256 nTokenHaircutAssetPV = tokenBalance .mul(nTokenAssetPV) .mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE])) .div(Constants.PERCENTAGE_DECIMALS) .div(nToken.totalSupply); // nToken.parameters is returned for use in liquidation return (nTokenHaircutAssetPV, nToken.parameters); } /// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and /// markets. The reason these are grouped together is because they both require storage reads of the same /// values. function _getPortfolioAndNTokenAssetValue( FreeCollateralFactors memory factors, int256 nTokenBalance, uint256 blockTime ) private view returns ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { // If the next asset matches the currency id then we need to calculate the cash group value if ( factors.portfolioIndex < factors.portfolio.length && factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId ) { // netPortfolioValue is in asset cash (netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue( factors.portfolio, factors.cashGroup, factors.market, blockTime, factors.portfolioIndex ); } else { netPortfolioValue = 0; } if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; nTokenParameters = 0; } } /// @notice Returns balance values for the bitmapped currency function _getBitmapBalanceValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns ( int256 cashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { int256 nTokenBalance; // prettier-ignore ( cashBalance, nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId); if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; } } /// @notice Returns portfolio value for the bitmapped currency function _getBitmapPortfolioValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns (int256) { (int256 netPortfolioValueUnderlying, bool bitmapHasDebt) = BitmapAssetsHandler.getifCashNetPresentValue( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, blockTime, factors.cashGroup, true // risk adjusted ); // Turns off has debt flag if it has changed bool contextHasAssetDebt = accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT; if (bitmapHasDebt && !contextHasAssetDebt) { // Turn on has debt accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; factors.updateContext = true; } else if (!bitmapHasDebt && contextHasAssetDebt) { // Turn off has debt accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; factors.updateContext = true; } // Return asset cash value return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying); } function _updateNetETHValue( uint256 currencyId, int256 netLocalAssetValue, FreeCollateralFactors memory factors ) private view returns (ETHRate memory) { ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId); // Converts to underlying first, ETH exchange rates are in underlying factors.netETHValue = factors.netETHValue.add( ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue)) ); return ethRate; } /// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account /// context needs to be updated. function getFreeCollateralStateful( address account, AccountContext memory accountContext, uint256 blockTime ) internal returns (int256, bool) { FreeCollateralFactors memory factors; bool hasCashDebt; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); if (netCashBalance < 0) hasCashDebt = true; int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(account, currencyBytes); if (netLocalAssetValue < 0) hasCashDebt = true; if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); // prettier-ignore ( int256 netPortfolioAssetValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioAssetValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { // NOTE: we must set the proper assetRate when we updateNetETHValue factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValue, factors); currencies = currencies << 16; } // Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e. // they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of // sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing // an account to do an extra free collateral check to turn off this setting. if ( accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT && !hasCashDebt ) { accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT; factors.updateContext = true; } return (factors.netETHValue, factors.updateContext); } /// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips /// all the update context logic. function getFreeCollateralView( address account, AccountContext memory accountContext, uint256 blockTime ) internal view returns (int256, int256[] memory) { FreeCollateralFactors memory factors; uint256 netLocalIndex; int256[] memory netLocalAssetValues = new int256[](10); if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); netLocalAssetValues[netLocalIndex] = netCashBalance .add(nTokenHaircutAssetValue) .add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue( accountContext.bitmapCurrencyId, netLocalAssetValues[netLocalIndex], factors ); netLocalIndex++; } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); int256 nTokenBalance; (netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances( account, currencyBytes ); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupView(currencyId); // prettier-ignore ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex] .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { factors.assetRate = AssetRate.buildAssetRateView(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors); netLocalIndex++; currencies = currencies << 16; } return (factors.netETHValue, netLocalAssetValues); } /// @notice Calculates the net value of a currency within a portfolio, this is a bit /// convoluted to fit into the stack frame function _calculateLiquidationAssetValue( FreeCollateralFactors memory factors, LiquidationFactors memory liquidationFactors, bytes2 currencyBytes, bool setLiquidationFactors, uint256 blockTime ) private returns (int256) { uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(liquidationFactors.account, currencyBytes); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); (int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; // If collateralCurrencyId is set to zero then this is a local currency liquidation if (setLiquidationFactors) { liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenParameters = nTokenParameters; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; } } else { factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } return netLocalAssetValue; } /// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information. function getLiquidationFactors( address account, AccountContext memory accountContext, uint256 blockTime, uint256 localCurrencyId, uint256 collateralCurrencyId ) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) { FreeCollateralFactors memory factors; LiquidationFactors memory liquidationFactors; // This is only set to reduce the stack size liquidationFactors.account = account; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); (int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioBalance = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance); factors.assetRate = factors.cashGroup.assetRate; ETHRate memory ethRate = _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); // If the bitmap currency id can only ever be the local currency where debt is held. // During enable bitmap we check that the account has no assets in their portfolio and // no cash debts. if (accountContext.bitmapCurrencyId == localCurrencyId) { liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // This will be the case during local currency or local fCash liquidation if (collateralCurrencyId == 0) { // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers. liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; liquidationFactors.nTokenParameters = nTokenParameters; } } } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); // This next bit of code here is annoyingly structured to get around stack size issues bool setLiquidationFactors; { uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); // Explicitly ensures that bitmap currency cannot be double counted require(tempId != accountContext.bitmapCurrencyId); setLiquidationFactors = (tempId == localCurrencyId && collateralCurrencyId == 0) || tempId == collateralCurrencyId; } int256 netLocalAssetValue = _calculateLiquidationAssetValue( factors, liquidationFactors, currencyBytes, setLiquidationFactors, blockTime ); uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors); if (currencyId == collateralCurrencyId) { // Ensure that this is set even if the cash group is not loaded, it will not be // loaded if the account only has a cash balance and no nTokens or assets liquidationFactors.collateralCashGroup.assetRate = factors.assetRate; liquidationFactors.collateralAssetAvailable = netLocalAssetValue; liquidationFactors.collateralETHRate = ethRate; } else if (currencyId == localCurrencyId) { // This branch will not be entered if bitmap is enabled liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers and it will have been set in // _calculateLiquidationAssetValue above because the account must have fCash assets, // there is no need to set cash group in this branch. } currencies = currencies << 16; } liquidationFactors.netETHValue = factors.netETHValue; require(liquidationFactors.netETHValue < 0, "Sufficient collateral"); // Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash // netting which will make further calculations incorrect. if (accountContext.assetArrayLength > 0) { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } return (liquidationFactors, factors.portfolio); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../valuation/AssetHandler.sol"; import "../markets/Market.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; library SettlePortfolioAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; using PortfolioHandler for PortfolioState; using AssetHandler for PortfolioAsset; /// @dev Returns a SettleAmount array for the assets that will be settled function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime) private pure returns (SettleAmount[] memory) { uint256 currenciesSettled; uint256 lastCurrencyId = 0; if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0); // Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio // NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause // a revert, must wrap in an unchecked. for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // Assets settle on exactly blockTime if (asset.getSettlementDate() > blockTime) continue; // Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this // will work for the first asset if (lastCurrencyId != asset.currencyId) { lastCurrencyId = asset.currencyId; currenciesSettled++; } } // Actual currency ids will be set as we loop through the portfolio and settle assets SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled); if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId; return settleAmounts; } /// @notice Settles a portfolio array function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime) internal returns (SettleAmount[] memory) { AssetRateParameters memory settlementRate; SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime); MarketParameters memory market; if (settleAmounts.length == 0) return settleAmounts; uint256 settleAmountIndex; for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; uint256 settleDate = asset.getSettlementDate(); // Settlement date is on block time exactly if (settleDate > blockTime) continue; // On the first loop the lastCurrencyId is already set. if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) { // New currency in the portfolio settleAmountIndex += 1; settleAmounts[settleAmountIndex].currencyId = asset.currencyId; } int256 assetCash; if (asset.assetType == Constants.FCASH_ASSET_TYPE) { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); assetCash = settlementRate.convertFromUnderlying(asset.notional); portfolioState.deleteAsset(i); } else if (AssetHandler.isLiquidityToken(asset.assetType)) { Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate); int256 fCash; (assetCash, fCash) = market.removeLiquidity(asset.notional); // Assets mature exactly on block time if (asset.maturity > blockTime) { // If fCash has not yet matured then add it to the portfolio _settleLiquidityTokenTofCash(portfolioState, i, fCash); } else { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); // If asset has matured then settle fCash to asset cash assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash)); portfolioState.deleteAsset(i); } } settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex] .netCashChange .add(assetCash); } return settleAmounts; } /// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future function _settleLiquidityTokenTofCash( PortfolioState memory portfolioState, uint256 index, int256 fCash ) private pure { PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index]; // If the liquidity token's maturity is still in the future then we change the entry to be // an idiosyncratic fCash entry with the net fCash amount. if (index != 0) { // Check to see if the previous index is the matching fCash asset, this will be the case when the // portfolio is sorted PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1]; if ( fCashAsset.currencyId == liquidityToken.currencyId && fCashAsset.maturity == liquidityToken.maturity && fCashAsset.assetType == Constants.FCASH_ASSET_TYPE ) { // This fCash asset has not matured if we are settling to fCash fCashAsset.notional = fCashAsset.notional.add(fCash); fCashAsset.storageState = AssetStorageState.Update; portfolioState.deleteAsset(index); } } // We are going to delete this asset anyway, convert to an fCash position liquidityToken.assetType = Constants.FCASH_ASSET_TYPE; liquidityToken.notional = fCash; liquidityToken.storageState = AssetStorageState.Update; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../markets/AssetRate.sol"; import "../../global/LibStorage.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; /** * Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash * at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues * to correctly reference all actual maturities. fCash asset notional values are stored in *absolute* * time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime. * Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on * newSettleTime and the absolute times (maturities) that the previous bitmap references. */ library SettleBitmapAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Bitmap for bytes32; /// @notice Given a bitmap for a cash group and timestamps, will settle all assets /// that have matured and remap the bitmap to correspond to the current time. function settleBitmappedCashGroup( address account, uint256 currencyId, uint256 oldSettleTime, uint256 blockTime ) internal returns (int256 totalAssetCash, uint256 newSettleTime) { bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId); // This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and // `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason // that lastSettleBit is inclusive is that it refers to newSettleTime which always less // than the current block time. newSettleTime = DateTime.getTimeUTC0(blockTime); // If newSettleTime == oldSettleTime lastSettleBit will be zero require(newSettleTime >= oldSettleTime); // dev: new settle time before previous // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until // the closest maturity that is less than newSettleTime. (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime); if (lastSettleBit == 0) return (totalAssetCash, newSettleTime); // Returns the next bit that is set in the bitmap uint256 nextBitNum = bitmap.getNextBitNum(); while (nextBitNum != 0 && nextBitNum <= lastSettleBit) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); totalAssetCash = totalAssetCash.add( _settlefCashAsset(account, currencyId, maturity, blockTime) ); // Turn the bit off now that it is settled bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } bytes32 newBitmap; while (nextBitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); (uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity); require(isValid); // dev: invalid new bit num newBitmap = newBitmap.setBit(newBitNum, true); // Turn the bit off now that it is remapped bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap); } /// @dev Stateful settlement function to settle a bitmapped asset. Deletes the /// asset from storage after calculating it. function _settlefCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 blockTime ) private returns (int256 assetCash) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); int256 notional = store[account][currencyId][maturity].notional; // Gets the current settlement rate or will store a new settlement rate if it does not // yet exist. AssetRateParameters memory rate = AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime); assetCash = rate.convertFromUnderlying(notional); delete store[account][currencyId][maturity]; return assetCash; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../markets/DateTime.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AssetHandler { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; function isLiquidityToken(uint256 assetType) internal pure returns (bool) { return assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX; } /// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method /// calculates the settlement date for any PortfolioAsset. function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) { require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type // 3 month tokens and fCash tokens settle at maturity if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1); // Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is: // maturity = tRef + marketLength // Here we calculate: // tRef = (maturity - marketLength) + 90 days return asset.maturity.sub(marketLength).add(Constants.QUARTER); } /// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity. /// The formula is: e^(-rate * timeToMaturity). function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)); expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue)); expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64); int256 discountFactor = ABDKMath64x64.toInt(expValue); return discountFactor; } /// @notice Present value of an fCash asset without any risk adjustments. function getPresentfCashValue( int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate); require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more /// heavily than the oracle rate given and vice versa for negative fCash. function getRiskAdjustedPresentfCashValue( CashGroupParameters memory cashGroup, int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor; if (notional > 0) { // If fCash is positive then discounting by a higher rate will result in a smaller // discount factor (e ^ -x), meaning a lower positive fCash value. discountFactor = getDiscountFactor( timeToMaturity, oracleRate.add(cashGroup.getfCashHaircut()) ); } else { uint256 debtBuffer = cashGroup.getDebtBuffer(); // If the adjustment exceeds the oracle rate we floor the value of the fCash // at the notional value. We don't want to require the account to hold more than // absolutely required. if (debtBuffer >= oracleRate) return notional; discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer); } require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Returns the non haircut claims on cash and fCash by the liquidity token. function getCashClaims(PortfolioAsset memory token, MarketParameters memory market) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity); fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity); } /// @notice Returns the haircut claims on cash and fCash function getHaircutCashClaims( PortfolioAsset memory token, MarketParameters memory market, CashGroupParameters memory cashGroup ) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch // This won't overflow, the liquidity token haircut is stored as an uint8 int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType)); assetCash = _calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity); fCash = _calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity); return (assetCash, fCash); } /// @dev This is here to clean up the stack in getHaircutCashClaims function _calcToken( int256 numerator, int256 tokens, int256 haircut, int256 liquidity ) private pure returns (int256) { return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity); } /// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists) function getLiquidityTokenValue( uint256 index, CashGroupParameters memory cashGroup, MarketParameters memory market, PortfolioAsset[] memory assets, uint256 blockTime, bool riskAdjusted ) internal view returns (int256, int256) { PortfolioAsset memory liquidityToken = assets[index]; { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex( cashGroup.maxMarketIndex, liquidityToken.maturity, blockTime ); // Liquidity tokens can never be idiosyncratic require(!idiosyncratic); // dev: idiosyncratic liquidity token // This market will always be initialized, if a liquidity token exists that means the // market has some liquidity in it. cashGroup.loadMarket(market, marketIndex, true, blockTime); } int256 assetCashClaim; int256 fCashClaim; if (riskAdjusted) { (assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup); } else { (assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market); } // Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and // in that case we know the previous asset will be the matching fCash asset if (index > 0) { PortfolioAsset memory maybefCash = assets[index - 1]; if ( maybefCash.assetType == Constants.FCASH_ASSET_TYPE && maybefCash.currencyId == liquidityToken.currencyId && maybefCash.maturity == liquidityToken.maturity ) { // Net off the fCashClaim here and we will discount it to present value in the second pass. // WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio! maybefCash.notional = maybefCash.notional.add(fCashClaim); // This state will prevent the fCash asset from being stored. maybefCash.storageState = AssetStorageState.RevertIfStored; return (assetCashClaim, 0); } } // If not matching fCash asset found then get the pv directly if (riskAdjusted) { int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate ); return (assetCashClaim, pv); } else { int256 pv = getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate); return (assetCashClaim, pv); } } /// @notice Returns present value of all assets in the cash group as asset cash and the updated /// portfolio index where the function has ended. /// @return the value of the cash group in asset cash function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex ) internal view returns (int256, uint256) { int256 presentValueAsset; int256 presentValueUnderlying; // First calculate value of liquidity tokens because we need to net off fCash value // before discounting to present value for (uint256 i = portfolioIndex; i < assets.length; i++) { if (!isLiquidityToken(assets[i].assetType)) continue; if (assets[i].currencyId != cashGroup.currencyId) break; (int256 assetCashClaim, int256 pv) = getLiquidityTokenValue( i, cashGroup, market, assets, blockTime, true // risk adjusted ); presentValueAsset = presentValueAsset.add(assetCashClaim); presentValueUnderlying = presentValueUnderlying.add(pv); } uint256 j = portfolioIndex; for (; j < assets.length; j++) { PortfolioAsset memory a = assets[j]; if (a.assetType != Constants.FCASH_ASSET_TYPE) continue; // If we hit a different currency id then we've accounted for all assets in this currency // j will mark the index where we don't have this currency anymore if (a.currencyId != cashGroup.currencyId) break; uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime); int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, a.notional, a.maturity, blockTime, oracleRate ); presentValueUnderlying = presentValueUnderlying.add(pv); } presentValueAsset = presentValueAsset.add( cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying) ); return (presentValueAsset, j); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; import "./Constants.sol"; import "../../interfaces/notional/IRewarder.sol"; import "../../interfaces/aave/ILendingPool.sol"; library LibStorage { /// @dev Offset for the initial slot in lib storage, gives us this number of storage slots /// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it. uint256 private constant STORAGE_SLOT_BASE = 1000000; /// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX /// in practice. It is possible to exceed that value during liquidation up to 14 potential assets. uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @dev Storage IDs for storage buckets. Each id maps to an internal storage /// slot used for a particular mapping /// WARNING: APPEND ONLY enum StorageId { Unused, AccountStorage, nTokenContext, nTokenAddress, nTokenDeposit, nTokenInitialization, Balance, Token, SettlementRate, CashGroup, Market, AssetsBitmap, ifCashBitmap, PortfolioArray, // WARNING: this nTokenTotalSupply storage object was used for a buggy version // of the incentives calculation. It should only be used for accounts who have // not claimed before the migration nTokenTotalSupply_deprecated, AssetRate, ExchangeRate, nTokenTotalSupply, SecondaryIncentiveRewarder, LendingPool } /// @dev Mapping from an account address to account context function getAccountStorage() internal pure returns (mapping(address => AccountContext) storage store) { uint256 slot = _getStorageSlot(StorageId.AccountStorage); assembly { store.slot := slot } } /// @dev Mapping from an nToken address to nTokenContext function getNTokenContextStorage() internal pure returns (mapping(address => nTokenContext) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenContext); assembly { store.slot := slot } } /// @dev Mapping from currency id to nTokenAddress function getNTokenAddressStorage() internal pure returns (mapping(uint256 => address) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenAddress); assembly { store.slot := slot } } /// @dev Mapping from currency id to uint32 fixed length array of /// deposit factors. Deposit shares and leverage thresholds are stored striped to /// reduce the number of storage reads. function getNTokenDepositStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenDeposit); assembly { store.slot := slot } } /// @dev Mapping from currency id to fixed length array of initialization factors, /// stored striped like deposit shares. function getNTokenInitStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenInitialization); assembly { store.slot := slot } } /// @dev Mapping from account to currencyId to it's balance storage for that currency function getBalanceStorage() internal pure returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Balance); assembly { store.slot := slot } } /// @dev Mapping from currency id to a boolean for underlying or asset token to /// the TokenStorage function getTokenStorage() internal pure returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Token); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its corresponding SettlementRate function getSettlementRateStorage() internal pure returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.SettlementRate); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its tightly packed cash group parameters function getCashGroupStorage() internal pure returns (mapping(uint256 => bytes32) storage store) { uint256 slot = _getStorageSlot(StorageId.CashGroup); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to settlement date for a market function getMarketStorage() internal pure returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.Market); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its assets bitmap function getAssetsBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => bytes32)) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetsBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance function getifCashBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.ifCashBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to its fixed length array of portfolio assets function getPortfolioArrayStorage() internal pure returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store) { uint256 slot = _getStorageSlot(StorageId.PortfolioArray); assembly { store.slot := slot } } function getDeprecatedNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated); assembly { store.slot := slot } } /// @dev Mapping from nToken address to its total supply values function getNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and asset for trading /// and free collateral. Mapping is from currency id to rate storage object. function getAssetRateStorage() internal pure returns (mapping(uint256 => AssetRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetRate); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and ETH for free /// collateral purposes. Mapping is from currency id to rate storage object. function getExchangeRateStorage() internal pure returns (mapping(uint256 => ETHRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.ExchangeRate); assembly { store.slot := slot } } /// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists function getSecondaryIncentiveRewarder() internal pure returns (mapping(address => IRewarder) storage store) { uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder); assembly { store.slot := slot } } /// @dev Returns the address of the lending pool function getLendingPool() internal pure returns (LendingPoolStorage storage store) { uint256 slot = _getStorageSlot(StorageId.LendingPool); assembly { store.slot := slot } } /// @dev Get the storage slot given a storage ID. /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function _getStorageSlot(StorageId storageId) private pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return uint256(storageId) + STORAGE_SLOT_BASE; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../AccountContextHandler.sol"; import "../markets/CashGroup.sol"; import "../valuation/AssetHandler.sol"; import "../../math/Bitmap.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library BitmapAssetsHandler { using SafeMath for uint256; using SafeInt256 for int256; using Bitmap for bytes32; using CashGroup for CashGroupParameters; using AccountContextHandler for AccountContext; function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) { mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); return store[account][currencyId]; } function setAssetsBitmap( address account, uint256 currencyId, bytes32 assetsBitmap ) internal { require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets"); mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); store[account][currencyId] = assetsBitmap; } function getifCashNotional( address account, uint256 currencyId, uint256 maturity ) internal view returns (int256 notional) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); return store[account][currencyId][maturity].notional; } /// @notice Adds multiple assets to a bitmap portfolio function addMultipleifCashAssets( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal { require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set uint256 currencyId = accountContext.bitmapCurrencyId; for (uint256 i; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets int256 finalNotional; finalNotional = addifCashAsset( account, currencyId, asset.maturity, accountContext.nextSettleTime, asset.notional ); if (finalNotional < 0) accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } } /// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory /// but not in storage. /// @return the updated assets bitmap and the final notional amount function addifCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 nextSettleTime, int256 notional ) internal returns (int256) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; (uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity); require(isExact); // dev: invalid maturity in set ifcash asset if (assetsBitmap.isBitSet(bitNum)) { // Bit is set so we read and update the notional amount int256 finalNotional = notional.add(fCashSlot.notional); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); // If the new notional is zero then turn off the bit if (finalNotional == 0) { assetsBitmap = assetsBitmap.setBit(bitNum, false); } setAssetsBitmap(account, currencyId, assetsBitmap); return finalNotional; } if (notional != 0) { // Bit is not set so we turn it on and update the mapping directly, no read required. require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(notional); assetsBitmap = assetsBitmap.setBit(bitNum, true); setAssetsBitmap(account, currencyId, assetsBitmap); } return notional; } /// @notice Returns the present value of an asset function getPresentValue( address account, uint256 currencyId, uint256 maturity, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256) { int256 notional = getifCashNotional(account, currencyId, maturity); // In this case the asset has matured and the total value is just the notional amount if (maturity <= blockTime) { return notional; } else { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); if (riskAdjusted) { return AssetHandler.getRiskAdjustedPresentfCashValue( cashGroup, notional, maturity, blockTime, oracleRate ); } else { return AssetHandler.getPresentfCashValue( notional, maturity, blockTime, oracleRate ); } } } function getNetPresentValueFromBitmap( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted, bytes32 assetsBitmap ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 pv = getPresentValue( account, currencyId, maturity, blockTime, cashGroup, riskAdjusted ); totalValueUnderlying = totalValueUnderlying.add(pv); if (pv < 0) hasDebt = true; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } } /// @notice Get the net present value of all the ifCash assets function getifCashNetPresentValue( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); return getNetPresentValueFromBitmap( account, currencyId, nextSettleTime, blockTime, cashGroup, riskAdjusted, assetsBitmap ); } /// @notice Returns the ifCash assets as an array function getifCashArray( address account, uint256 currencyId, uint256 nextSettleTime ) internal view returns (PortfolioAsset[] memory) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 notional = getifCashNotional(account, currencyId, maturity); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notional; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../interfaces/chainlink/AggregatorV2V3Interface.sol"; import "../../interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) /// - aToken: Aave interest bearing tokens enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // Accumulator for incentives that the account no longer has a claim over uint256 accountIncentiveDebt; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; // Reserved bytes for future usage bytes15 _unused; // Set to true if a secondary rewarder is set bool hasSecondaryRewarder; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // Incentives that the account no longer has a claim over uint56 accountIncentiveDebt; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. This is the deprecated version struct nTokenTotalSupplyStorage_deprecated { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // How many NOTE incentives should be issued per nToken in 1e18 precision uint128 accumulatedNOTEPerNToken; // Last timestamp when the accumulation happened uint32 lastAccumulatedTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 accountIncentiveDebt; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Each bit set in this mask marks where an active market should be in the bitmap // if the first bit refers to the reference time. Used to detect idiosyncratic // fcash in the nToken accounts bytes32 internal constant ACTIVE_MARKETS_MASK = ( MSB >> ( 90 - 1) | // 3 month MSB >> (105 - 1) | // 6 month MSB >> (135 - 1) | // 1 year MSB >> (147 - 1) | // 2 year MSB >> (183 - 1) | // 5 year MSB >> (211 - 1) | // 10 year MSB >> (251 - 1) // 20 year ); // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library DateTime { using SafeMath for uint256; /// @notice Returns the current reference time which is how all the AMM dates are calculated. function getReferenceTime(uint256 blockTime) internal pure returns (uint256) { require(blockTime >= Constants.QUARTER); return blockTime - (blockTime % Constants.QUARTER); } /// @notice Truncates a date to midnight UTC time function getTimeUTC0(uint256 time) internal pure returns (uint256) { require(time >= Constants.DAY); return time - (time % Constants.DAY); } /// @notice These are the predetermined market offsets for trading /// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group. function getTradedMarket(uint256 index) internal pure returns (uint256) { if (index == 1) return Constants.QUARTER; if (index == 2) return 2 * Constants.QUARTER; if (index == 3) return Constants.YEAR; if (index == 4) return 2 * Constants.YEAR; if (index == 5) return 5 * Constants.YEAR; if (index == 6) return 10 * Constants.YEAR; if (index == 7) return 20 * Constants.YEAR; revert("Invalid index"); } /// @notice Determines if the maturity falls on one of the valid on chain market dates. function isValidMarketMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); if (maturity % Constants.QUARTER != 0) return false; uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true; } return false; } /// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case. function isValidMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { uint256 tRef = DateTime.getReferenceTime(blockTime); uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex)); // Cannot trade past max maturity if (maturity > maxMaturity) return false; // prettier-ignore (/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity); return isValid; } /// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic /// will return the nearest market index that is larger than the maturity. /// @return uint marketIndex, bool isIdiosyncratic function getMarketIndex( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (uint256, bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i)); // If market matches then is not idiosyncratic if (marketMaturity == maturity) return (i, false); // Returns the market that is immediately greater than the maturity if (marketMaturity > maturity) return (i, true); } revert("CG: no market found"); } /// @notice Given a bit number and the reference time of the first bit, returns the bit number /// of a given maturity. /// @return bitNum and a true or false if the maturity falls on the exact bit function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool) { uint256 blockTimeUTC0 = getTimeUTC0(blockTime); // Maturities must always divide days evenly if (maturity % Constants.DAY != 0) return (0, false); // Maturity cannot be in the past if (blockTimeUTC0 >= maturity) return (0, false); // Overflow check done above // daysOffset has no remainders, checked above uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY; // These if statements need to fall through to the next one if (daysOffset <= Constants.MAX_DAY_OFFSET) { return (daysOffset, true); } else if (daysOffset <= Constants.MAX_WEEK_OFFSET) { // (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0 // (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion // This returns the offset from the previous max offset in days uint256 offsetInDays = daysOffset - Constants.MAX_DAY_OFFSET + (blockTimeUTC0 % Constants.WEEK) / Constants.DAY; return ( // This converts the offset in days to its corresponding bit position, truncating down // if it does not divide evenly into DAYS_IN_WEEK Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK, (offsetInDays % Constants.DAYS_IN_WEEK) == 0 ); } else if (daysOffset <= Constants.MAX_MONTH_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_WEEK_OFFSET + (blockTimeUTC0 % Constants.MONTH) / Constants.DAY; return ( Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH, (offsetInDays % Constants.DAYS_IN_MONTH) == 0 ); } else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_MONTH_OFFSET + (blockTimeUTC0 % Constants.QUARTER) / Constants.DAY; return ( Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER, (offsetInDays % Constants.DAYS_IN_QUARTER) == 0 ); } // This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20 // year max maturity return (256, false); } /// @notice Given a bit number and a block time returns the maturity that the bit number /// should reference. Bit numbers are one indexed. function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum) internal pure returns (uint256) { require(bitNum != 0); // dev: cash group get maturity from bit num is zero require(bitNum <= 256); // dev: cash group get maturity from bit num overflow uint256 blockTimeUTC0 = getTimeUTC0(blockTime); uint256 firstBit; if (bitNum <= Constants.WEEK_BIT_OFFSET) { return blockTimeUTC0 + bitNum * Constants.DAY; } else if (bitNum <= Constants.MONTH_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_DAY_OFFSET * Constants.DAY - // This backs up to the day that is divisible by a week (blockTimeUTC0 % Constants.WEEK); return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK; } else if (bitNum <= Constants.QUARTER_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_WEEK_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.MONTH); return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH; } else { firstBit = blockTimeUTC0 + Constants.MAX_MONTH_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.QUARTER); return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER; } } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; interface IRewarder { function claimRewards( address account, uint16 currencyId, uint256 nTokenBalanceBefore, uint256 nTokenBalanceAfter, int256 netNTokenSupplyChange, uint256 NOTETokensClaimed ) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; struct LendingPoolStorage { ILendingPool lendingPool; } interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (ReserveData memory); // 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} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TokenHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenSupply.sol"; import "../../math/SafeInt256.sol"; import "../../external/MigrateIncentives.sol"; import "../../../interfaces/notional/IRewarder.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Incentives { using SafeMath for uint256; using SafeInt256 for int256; /// @notice Calculates the total incentives to claim including those claimed under the previous /// less accurate calculation. Once an account is migrated it will only claim incentives under /// the more accurate regime function calculateIncentivesToClaim( BalanceState memory balanceState, address tokenAddress, uint256 accumulatedNOTEPerNToken, uint256 finalNTokenBalance ) internal view returns (uint256 incentivesToClaim) { if (balanceState.lastClaimTime > 0) { // If lastClaimTime is set then the account had incentives under the // previous regime. Will calculate the final amount of incentives to claim here // under the previous regime. incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation( tokenAddress, balanceState.storedNTokenBalance.toUint(), balanceState.lastClaimTime, // In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under // the old calculation balanceState.accountIncentiveDebt ); // This marks the account as migrated and lastClaimTime will no longer be used balanceState.lastClaimTime = 0; // This value will be set immediately after this, set this to zero so that the calculation // establishes a new baseline. balanceState.accountIncentiveDebt = 0; } // If an account was migrated then they have no accountIncentivesDebt and should accumulate // incentives based on their share since the new regime calculation started. // If an account is just initiating their nToken balance then storedNTokenBalance will be zero // and they will have no incentives to claim. // This calculation uses storedNTokenBalance which is the balance of the account up until this point, // this is important to ensure that the account does not claim for nTokens that they will mint or // redeem on a going forward basis. // The calculation below has the following precision: // storedNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION incentivesToClaim = incentivesToClaim.add( balanceState.storedNTokenBalance.toUint() .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION) .sub(balanceState.accountIncentiveDebt) ); // Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion // of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance // here instead of storedNTokenBalance to mark the overall incentives claim that the account // does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt // because accumulatedNOTEPerNToken is already an aggregated value. // The calculation below has the following precision: // finalNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION balanceState.accountIncentiveDebt = finalNTokenBalance .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION); } /// @notice Incentives must be claimed every time nToken balance changes. /// @dev BalanceState.accountIncentiveDebt is updated in place here function claimIncentives( BalanceState memory balanceState, address account, uint256 finalNTokenBalance ) internal returns (uint256 incentivesToClaim) { uint256 blockTime = block.timestamp; address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId); // This will updated the nToken storage and return what the accumulatedNOTEPerNToken // is up until this current block time in 1e18 precision uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply( tokenAddress, balanceState.netNTokenSupplyChange, blockTime ); incentivesToClaim = calculateIncentivesToClaim( balanceState, tokenAddress, accumulatedNOTEPerNToken, finalNTokenBalance ); // If a secondary incentive rewarder is set, then call it IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress); if (address(rewarder) != address(0)) { rewarder.claimRewards( account, balanceState.currencyId, // When this method is called from finalize, the storedNTokenBalance has not // been updated to finalNTokenBalance yet so this is the balance before the change. balanceState.storedNTokenBalance.toUint(), finalNTokenBalance, // When the rewarder is called, totalSupply has been updated already so may need to // adjust its calculation using the net supply change figure here. Supply change // may be zero when nTokens are transferred. balanceState.netNTokenSupplyChange, incentivesToClaim ); } if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../global/Deployments.sol"; import "./protocols/AaveHandler.sol"; import "./protocols/CompoundHandler.sol"; import "./protocols/GenericToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @notice Handles all external token transfers and events library TokenHandler { using SafeInt256 for int256; using SafeMath for uint256; function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][false]; tokenStorage.maxCollateralBalance = maxCollateralBalance; } function getAssetToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, false); } function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, true); } /// @notice Gets token data for a particular currency id, if underlying is set to true then returns /// the underlying token. (These may not always exist) function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][underlying]; return Token({ tokenAddress: tokenStorage.tokenAddress, hasTransferFee: tokenStorage.hasTransferFee, // No overflow, restricted on storage decimals: int256(10**tokenStorage.decimalPlaces), tokenType: tokenStorage.tokenType, maxCollateralBalance: tokenStorage.maxCollateralBalance }); } /// @notice Sets a token for a currency id. function setToken( uint256 currencyId, bool underlying, TokenStorage memory tokenStorage ) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) { // Hardcoded parameters for ETH just to make sure we don't get it wrong. TokenStorage storage ts = store[currencyId][true]; ts.tokenAddress = address(0); ts.hasTransferFee = false; ts.tokenType = TokenType.Ether; ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES; ts.maxCollateralBalance = 0; return; } // Check token address require(tokenStorage.tokenAddress != address(0), "TH: address is zero"); // Once a token is set we cannot override it. In the case that we do need to do change a token address // then we should explicitly upgrade this method to allow for a token to be changed. Token memory token = _getToken(currencyId, underlying); require( token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0), "TH: token cannot be reset" ); require(0 < tokenStorage.decimalPlaces && tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals"); // Validate token type require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once if (underlying) { // Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily // during mint and redeem actions. require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent } else { require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent } if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) { // Set the approval for the underlying so that we can mint cTokens or aTokens Token memory underlyingToken = getUnderlyingToken(currencyId); // cTokens call transfer from the tokenAddress, but aTokens use the LendingPool // to initiate all transfers address approvalAddress = tokenStorage.tokenType == TokenType.cToken ? tokenStorage.tokenAddress : address(LibStorage.getLendingPool().lendingPool); // ERC20 tokens should return true on success for an approval, but Tether // does not return a value here so we use the NonStandard interface here to // check that the approval was successful. IEIP20NonStandard(underlyingToken.tokenAddress).approve( approvalAddress, type(uint256).max ); GenericToken.checkReturnCode(); } store[currencyId][underlying] = tokenStorage; } /** * @notice If a token is mintable then will mint it. At this point we expect to have the underlying * balance in the contract already. * @param assetToken the asset token to mint * @param underlyingAmountExternal the amount of underlying to transfer to the mintable token * @return the amount of asset tokens minted, will always be a positive integer */ function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) { // aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this // value in internal accounting since it will not allow individual users to accrue aToken interest. Use the // scaledBalanceOf function call instead for internal accounting. bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); if (assetToken.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); AaveHandler.mint(underlyingToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { CompoundHandler.mint(assetToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cETH) { CompoundHandler.mintCETH(assetToken); } else { revert(); // dev: non mintable token } uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); // This is the starting and ending balance in external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } /** * @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance * to the account * @param assetToken asset token to redeem * @param currencyId the currency id of the token * @param account account to transfer the underlying to * @param assetAmountExternal the amount to transfer in asset token denomination and external precision * @return the actual amount of underlying tokens transferred. this is used as a return value back to the * user, is not used for internal accounting purposes */ function redeem( Token memory assetToken, uint256 currencyId, address account, uint256 assetAmountExternal ) internal returns (int256) { uint256 transferAmount; if (assetToken.tokenType == TokenType.cETH) { transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal); } else { Token memory underlyingToken = getUnderlyingToken(currencyId); if (assetToken.tokenType == TokenType.aToken) { transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal); } else { revert(); // dev: non redeemable token } } // Use the negative value here to signify that assets have left the protocol return SafeInt256.toInt(transferAmount).neg(); } /// @notice Handles transfers into and out of the system denominated in the external token decimal /// precision. function transfer( Token memory token, address account, uint256 currencyId, int256 netTransferExternal ) internal returns (int256 actualTransferExternal) { // This will be true in all cases except for deposits where the token has transfer fees. For // aTokens this value is set before convert from scaled balances to principal plus interest actualTransferExternal = netTransferExternal; if (token.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); // aTokens need to be converted when we handle the transfer since the external balance format // is not the same as the internal balance format that we use netTransferExternal = AaveHandler.convertFromScaledBalanceExternal( underlyingToken.tokenAddress, netTransferExternal ); } if (netTransferExternal > 0) { // Deposits must account for transfer fees. int256 netDeposit = _deposit(token, account, uint256(netTransferExternal)); // If an aToken has a transfer fee this will still return a balance figure // in scaledBalanceOf terms due to the selector if (token.hasTransferFee) actualTransferExternal = netDeposit; } else if (token.tokenType == TokenType.Ether) { // netTransferExternal can only be negative or zero at this point GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg())); } else { GenericToken.safeTransferOut( token.tokenAddress, account, // netTransferExternal is zero or negative here uint256(netTransferExternal.neg()) ); } } /// @notice Handles token deposits into Notional. If there is a transfer fee then we must /// calculate the net balance after transfer. Amounts are denominated in the destination token's /// precision. function _deposit( Token memory token, address account, uint256 amount ) private returns (int256) { uint256 startingBalance; uint256 endingBalance; bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; if (token.hasTransferFee) { startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } GenericToken.safeTransferIn(token.tokenAddress, account, amount); if (token.hasTransferFee || token.maxCollateralBalance > 0) { // If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably // the correct behavior because if collateral accrues interest over time we should not somehow go over the // maxCollateralBalance due to the passage of time. endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } if (token.maxCollateralBalance > 0) { int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance)); // Max collateral balance is stored as uint72, no overflow require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance } // Math is done in uint inside these statements and will revert on negative if (token.hasTransferFee) { return SafeInt256.toInt(endingBalance.sub(startingBalance)); } else { return SafeInt256.toInt(amount); } } function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) { // If token decimals > INTERNAL_TOKEN_PRECISION: // on deposit: resulting dust will accumulate to protocol // on withdraw: protocol may lose dust amount. However, withdraws are only calculated based // on a conversion from internal token precision to external token precision so therefore dust // amounts cannot be specified for withdraws. // If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the // end of amount and will not result in dust. if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals); } function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) { if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; // If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount // by adding a number of zeros to the end and will not result in dust. // If token decimals < INTERNAL_TOKEN_PRECISION: // on deposit: Deposits are specified in external token precision and there is no loss of precision when // tokens are converted from external to internal precision // on withdraw: this calculation will round down such that the protocol retains the residual cash balance return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION); } function transferIncentive(address account, uint256 tokensToTransfer) internal { GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./Bitmap.sol"; /** * Packs an uint value into a "floating point" storage slot. Used for storing * lastClaimIntegralSupply values in balance storage. For these values, we don't need * to maintain exact precision but we don't want to be limited by storage size overflows. * * A floating point value is defined by the 48 most significant bits and an 8 bit number * of bit shifts required to restore its precision. The unpacked value will always be less * than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1. */ library FloatingPoint56 { function packTo56Bits(uint256 value) internal pure returns (uint56) { uint256 bitShift; // If the value is over the uint48 max value then we will shift it down // given the index of the most significant bit. We store this bit shift // in the least significant byte of the 56 bit slot available. if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47); uint256 shiftedValue = value >> bitShift; return uint56((shiftedValue << 8) | bitShift); } function unpackFrom56Bits(uint256 value) internal pure returns (uint256) { // The least significant 8 bits will be the amount to bit shift uint256 bitShift = uint256(uint8(value)); return ((value >> 8) << bitShift); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenSupply.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenHandler { using SafeInt256 for int256; /// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning /// two constants to each other. uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @notice Returns an account context object that is specific to nTokens. function getNTokenContext(address tokenAddress) internal view returns ( uint16 currencyId, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters; } /// @notice Returns the nToken token address for a given currency function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) { mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage(); return store[currencyId]; } /// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be /// reset once this is set. function setNTokenAddress(uint16 currencyId, address tokenAddress) internal { mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage(); require(addressStore[currencyId] == address(0), "PT: token address exists"); mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage(); nTokenContext storage context = contextStore[tokenAddress]; require(context.currencyId == 0, "PT: currency exists"); // This will initialize all other context slots to zero context.currencyId = currencyId; addressStore[currencyId] = tokenAddress; } /// @notice Set nToken token collateral parameters function setNTokenCollateralParameters( address tokenAddress, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut"); // The pv haircut percentage must be less than the liquidation percentage or else liquidators will not // get profit for liquidating nToken. require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut"); // Ensure that the cash withholding buffer is greater than the residual purchase incentive or // the nToken may not have enough cash to pay accounts to buy its negative ifCash require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts"); bytes5 parameters = (bytes5(uint40(residualPurchaseIncentive10BPS)) | (bytes5(uint40(pvHaircutPercentage)) << 8) | (bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) | (bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) | (bytes5(uint40(liquidationHaircutPercentage)) << 32)); // Set the parameters context.nTokenParameters = parameters; } /// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different /// contract, aside from the native NOTE token incentives. function setSecondaryRewarder( uint16 currencyId, IRewarder rewarder ) internal { address tokenAddress = nTokenAddress(currencyId); // nToken must exist for a secondary rewarder require(tokenAddress != address(0)); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; // Setting the rewarder to address(0) will disable it. We use a context setting here so that // we can save a storage read before getting the rewarder context.hasSecondaryRewarder = (address(rewarder) != address(0)); LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder; } /// @notice Returns the secondary rewarder if it is set function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; if (context.hasSecondaryRewarder) { return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress]; } else { return IRewarder(address(0)); } } function setArrayLengthAndInitializedTime( address tokenAddress, uint8 arrayLength, uint256 lastInitializedTime ) internal { require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.lastInitializedTime = uint32(lastInitializedTime); context.assetArrayLength = arrayLength; } /// @notice Returns the array of deposit shares and leverage thresholds for nTokens function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory depositShares, int256[] memory leverageThresholds) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; (depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false); } /// @notice Sets the deposit parameters /// @dev We pack the values in alternating between the two parameters into either one or two // storage slots depending on the number of markets. This is to save storage reads when we use the parameters. function setDepositParameters( uint256 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) internal { require( depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: deposit share length" ); require(depositShares.length == leverageThresholds.length, "PT: leverage share length"); uint256 shareSum; for (uint256 i; i < depositShares.length; i++) { // This cannot overflow in uint 256 with 9 max slots shareSum = shareSum + depositShares[i]; require( leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION, "PT: leverage threshold" ); } // Total deposit share must add up to 100% require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum"); mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; _setParameters(depositParameters, depositShares, leverageThresholds); } /// @notice Sets the initialization parameters for the markets, these are read only when markets /// are initialized function setInitializationParameters( uint256 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) internal { require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length"); require(proportions.length == annualizedAnchorRates.length, "PT: proportions length"); for (uint256 i; i < proportions.length; i++) { // Proportions must be between zero and the rate precision require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero"); require( proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION, "PT: invalid proportion" ); } mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; _setParameters(initParameters, annualizedAnchorRates, proportions); } /// @notice Returns the array of initialization parameters for a given currency. function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; (annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true); } function _getParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint256 maxMarketIndex, bool noUnset ) private view returns (int256[] memory, int256[] memory) { uint256 index = 0; int256[] memory array1 = new int256[](maxMarketIndex); int256[] memory array2 = new int256[](maxMarketIndex); for (uint256 i; i < maxMarketIndex; i++) { array1[i] = slot[index]; index++; array2[i] = slot[index]; index++; if (noUnset) { require(array1[i] > 0 && array2[i] > 0, "PT: init value zero"); } } return (array1, array2); } function _setParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint32[] calldata array1, uint32[] calldata array2 ) private { uint256 index = 0; for (uint256 i = 0; i < array1.length; i++) { slot[index] = array1[i]; index++; slot[index] = array2[i]; index++; } } function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); // prettier-ignore ( uint256 totalSupply, /* accumulatedNOTEPerNToken */, /* lastAccumulatedTime */ ) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); // prettier-ignore ( nToken.cashBalance, /* nTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId); } /// @notice Uses buildCashGroupStateful function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId) internal { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId); } /// @notice Uses buildCashGroupView function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId) internal view { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupView(currencyId); } /// @notice Returns the next settle time for the nToken which is 1 quarter away function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) { if (nToken.lastInitializedTime == 0) return 0; return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenSupply { using SafeInt256 for int256; using SafeMath for uint256; /// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating /// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead. function getStoredNTokenSupplyFactors(address tokenAddress) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; totalSupply = nTokenStorage.totalSupply; // NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken // must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken; lastAccumulatedTime = nTokenStorage.lastAccumulatedTime; } /// @notice Returns the updated accumulated NOTE per nToken for calculating incentives function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { ( totalSupply, accumulatedNOTEPerNToken, lastAccumulatedTime ) = getStoredNTokenSupplyFactors(tokenAddress); // nToken totalSupply is never allowed to drop to zero but we check this here to avoid // divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not // zero to avoid a massive accumulation amount on initialization. if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) { // prettier-ignore ( /* currencyId */, uint256 emissionRatePerYear, /* initializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(tokenAddress); uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE( // Emission rate is denominated in whole tokens, scale to 1e8 decimals here emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)), // Time since last accumulation (overflow checked above) blockTime - lastAccumulatedTime, totalSupply ); accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken); require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow } } /// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision function _calculateAdditionalNOTE( uint256 emissionRatePerYear, uint256 timeSinceLastAccumulation, uint256 totalSupply ) private pure returns (uint256) { // If we use 18 decimal places as the accumulation precision then we will overflow uint128 when // a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max // NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe // using 18 decimal places and uint128 storage slot // timeSinceLastAccumulation (SECONDS) // accumulatedNOTEPerSharePrecision (1e18) // emissionRatePerYear (INTERNAL_TOKEN_PRECISION) // DIVIDE BY // YEAR (SECONDS) // totalSupply (INTERNAL_TOKEN_PRECISION) return timeSinceLastAccumulation .mul(Constants.INCENTIVE_ACCUMULATION_PRECISION) .mul(emissionRatePerYear) .div(Constants.YEAR) // totalSupply > 0 is checked in the calling function .div(totalSupply); } /// @notice Updates the nToken token supply amount when minting or redeeming. /// @param tokenAddress address of the nToken /// @param netChange positive or negative change to the total nToken supply /// @param blockTime current block time /// @return accumulatedNOTEPerNToken updated to the given block time function changeNTokenSupply( address tokenAddress, int256 netChange, uint256 blockTime ) internal returns (uint256) { ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, /* uint256 lastAccumulatedTime */ ) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime); // Update storage variables mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; int256 newTotalSupply = int256(totalSupply).add(netChange); // We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to // exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check. require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow nTokenStorage.totalSupply = uint96(newTotalSupply); // NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what // the user would see if querying the view function nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken); require(blockTime < type(uint32).max); // dev: block time overflow nTokenStorage.lastAccumulatedTime = uint32(blockTime); return accumulatedNOTEPerNToken; } /// @notice Called by governance to set the new emission rate function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal { // Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the // emission rate changeNTokenSupply(tokenAddress, 0, blockTime); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.incentiveAnnualEmissionRate = newEmissionsRate; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "../internal/nToken/nTokenHandler.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @notice Deployed library for migration of incentives from the old (inaccurate) calculation * to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate * calculation is inside `Incentives.sol` and this library holds the legacy calculation. System * migration code can be found in `MigrateIncentivesFix.sol` */ library MigrateIncentives { using SafeMath for uint256; /// @notice Calculates the claimable incentives for a particular nToken and account in the /// previous regime. This should only ever be called ONCE for an account / currency combination /// to get the incentives accrued up until the migration date. function migrateAccountFromPreviousCalculation( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) external view returns (uint256) { ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) = _getMigratedIncentiveValues(tokenAddress); // This if statement should never be true but we return 0 just in case if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0; // No overflow here, checked above. All incentives are claimed up until finalMigrationTime // using the finalTotalIntegralSupply. Both these values are set on migration and will not // change. uint256 timeSinceMigration = finalMigrationTime - lastClaimTime; // (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR uint256 incentiveRate = timeSinceMigration .mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) // Migration emission rate is stored as is, denominated in whole tokens .mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) .div(Constants.YEAR); // Returns the average supply using the integral of the total supply. uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration); if (avgTotalSupply == 0) return 0; uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply); // incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8 incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION)); return incentivesToClaim; } function _getMigratedIncentiveValues( address tokenAddress ) private view returns ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) { mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress]; // The total supply value is overridden as emissionRatePerYear during the initialization finalEmissionRatePerYear = d_nTokenStorage.totalSupply; finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply; finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce /// gas costs for immutable addresses. They must be updated per environment that Notional /// is deployed to. library Deployments { address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../../global/Types.sol"; import "../../../global/LibStorage.sol"; import "../../../math/SafeInt256.sol"; import "../TokenHandler.sol"; import "../../../../interfaces/aave/IAToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AaveHandler { using SafeMath for uint256; using SafeInt256 for int256; int256 internal constant RAY = 1e27; int256 internal constant halfRAY = RAY / 2; bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector; /** * @notice Mints an amount of aTokens corresponding to the the underlying. * @param underlyingToken address of the underlying token to pass to Aave * @param underlyingAmountExternal amount of underlying to deposit, in external precision */ function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal { // In AaveV3 this method is renamed to supply() but deposit() is still available for // backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755 // We use deposit here so that mainnet-fork tests against Aave v2 will pass. LibStorage.getLendingPool().lendingPool.deposit( underlyingToken.tokenAddress, underlyingAmountExternal, address(this), 0 ); } /** * @notice Redeems and sends an amount of aTokens to the specified account * @param underlyingToken address of the underlying token to pass to Aave * @param account account to receive the underlying * @param assetAmountExternal amount of aTokens in scaledBalanceOf terms */ function redeem( Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { underlyingAmountExternal = convertFromScaledBalanceExternal( underlyingToken.tokenAddress, SafeInt256.toInt(assetAmountExternal) ).toUint(); LibStorage.getLendingPool().lendingPool.withdraw( underlyingToken.tokenAddress, underlyingAmountExternal, account ); } /** * @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest) * and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional * claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will * receive future Aave interest. * @dev There is no loss of precision within this function since it does the exact same calculation as Aave. * @param currencyId is the currency id * @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must * be positive in this function, this method is only called when depositing aTokens directly * @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will * be in external precision. */ function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId); // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress); // Mimic the WadRay math performed by Aave (but do it in int256 instead) int256 halfIndex = index / 2; // Overflow will occur when: (a * RAY + halfIndex) > int256.max require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY); // if index is zero then this will revert return (assetAmountExternal * RAY + halfIndex) / index; } /** * @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision) * and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest * that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions. * @dev There is no loss of precision because this does exactly what Aave's calculation would do * @param underlyingToken token address of the underlying asset * @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from * Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or * withdrawn (negative). * @return netBalanceExternal the Aave balanceOf equivalent as a signed integer */ function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) { if (netScaledBalanceExternal == 0) return 0; // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken); // Use the absolute value here so that the halfRay rounding is applied correctly for negative values int256 abs = netScaledBalanceExternal.abs(); // Mimic the WadRay math performed by Aave (but do it in int256 instead) // Overflow will occur when: (abs * index + halfRay) > int256.max // Here the first term is computed at compile time so it just does a division. If index is zero then // solidity will revert. require(abs <= (type(int256).max - halfRAY) / index); int256 absScaled = (abs * index + halfRAY) / RAY; return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg(); } /// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is /// always positive even though we are converting to a signed int function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) { return SafeInt256.toInt( LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./GenericToken.sol"; import "../../../../interfaces/compound/CErc20Interface.sol"; import "../../../../interfaces/compound/CEtherInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../global/Types.sol"; library CompoundHandler { using SafeMath for uint256; // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; function mintCETH(Token memory token) internal { // Reverts on error CEtherInterface(token.tokenAddress).mint{value: msg.value}(); } function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) { uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint"); } function redeemCETH( Token memory assetToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = address(this).balance; uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = address(this).balance; underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.transferNativeTokenOut(account, underlyingAmountExternal); } function redeem( Token memory assetToken, Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../../../../interfaces/IEIP20NonStandard.sol"; library GenericToken { bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector; /** * @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows * for overriding the balanceOf selector to use scaledBalanceOf for aTokens */ function checkBalanceViaSelector( address token, address account, bytes4 balanceOfSelector ) internal returns (uint256 balance) { (bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account)); require(success); (balance) = abi.decode(returnData, (uint256)); } function transferNativeTokenOut( address account, uint256 amount ) internal { // This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying // ETH they will have to withdraw the cETH token and then redeem it manually. payable(account).transfer(amount); } function safeTransferOut( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transfer(account, amount); checkReturnCode(); } function safeTransferIn( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transferFrom(account, address(this), amount); checkReturnCode(); } function checkReturnCode() internal pure { bool success; uint256[1] memory result; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := 1 // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(result, 0, 32) success := mload(result) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "ERC20"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); function UNDERLYING_ASSET_ADDRESS() external view returns (address); function symbol() external view returns (string memory); } interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } interface IATokenFull is IScaledBalanceToken, IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; import "./CTokenInterface.sol"; interface CErc20Interface { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CEtherInterface { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface IEIP20NonStandard { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved */ function approve(address spender, uint256 amount) external; /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CTokenInterface { /*** User Interface ***/ function underlying() external view returns (address); function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/Types.sol"; import "../global/Constants.sol"; /// @notice Helper methods for bitmaps, they are big-endian and 1-indexed. library Bitmap { /// @notice Set a bit on or off in a bitmap, index is 1-indexed function setBit( bytes32 bitmap, uint256 index, bool setOn ) internal pure returns (bytes32) { require(index >= 1 && index <= 256); // dev: set bit index bounds if (setOn) { return bitmap | (Constants.MSB >> (index - 1)); } else { return bitmap & ~(Constants.MSB >> (index - 1)); } } /// @notice Check if a bit is set function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) { require(index >= 1 && index <= 256); // dev: set bit index bounds return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB; } /// @notice Count the total bits set function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) { uint256 x = uint256(bitmap); x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555); x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333); x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4); x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F); x = x + (x >> 16); x = x + (x >> 32); x = x + (x >> 64); return (x & 0xFF) + (x >> 128 & 0xFF); } // Does a binary search over x to get the position of the most significant bit function getMSB(uint256 x) internal pure returns (uint256 msb) { // If x == 0 then there is no MSB and this method will return zero. That would // be the same as the return value when x == 1 (MSB is zero indexed), so instead // we have this require here to ensure that the values don't get mixed up. require(x != 0); // dev: get msb zero value if (x >= 0x100000000000000000000000000000000) { x >>= 128; msb += 128; } if (x >= 0x10000000000000000) { x >>= 64; msb += 64; } if (x >= 0x100000000) { x >>= 32; msb += 32; } if (x >= 0x10000) { x >>= 16; msb += 16; } if (x >= 0x100) { x >>= 8; msb += 8; } if (x >= 0x10) { x >>= 4; msb += 4; } if (x >= 0x4) { x >>= 2; msb += 2; } if (x >= 0x2) msb += 1; // No need to shift xc anymore } /// @dev getMSB returns a zero indexed bit number where zero is the first bit counting /// from the right (little endian). Asset Bitmaps are counted from the left (big endian) /// and one indexed. function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) { // Short circuit the search if bitmap is all zeros if (bitmap == 0x00) return 0; return 255 - getMSB(uint256(bitmap)) + 1; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../balances/TokenHandler.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol"; library ExchangeRate { using SafeInt256 for int256; /// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are /// always applied in this method. /// @param er exchange rate object from base to ETH /// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) { int256 multiplier = balance > 0 ? er.haircut : er.buffer; // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals) // Therefore the result is in ethDecimals int256 result = balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div( er.rateDecimals ); return result; } /// @notice Converts the balance denominated in ETH to the equivalent value in a base currency. /// Buffers and haircuts ARE NOT applied in this method. /// @param er exchange rate object from base to ETH /// @param balance amount (denominated in ETH) to convert function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) { // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals / rateDecimals int256 result = balance.mul(er.rateDecimals).div(er.rate); return result; } /// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in /// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals /// @param baseER base exchange rate struct /// @param quoteER quote exchange rate struct function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER) internal pure returns (int256) { return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate); } /// @notice Returns an ETHRate object used to calculate free collateral function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) { mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage(); ETHRateStorage storage ethStorage = store[currencyId]; int256 rateDecimals; int256 rate; if (currencyId == Constants.ETH_CURRENCY_ID) { // ETH rates will just be 1e18, but will still have buffers, haircuts, // and liquidation discounts rateDecimals = Constants.ETH_DECIMALS; rate = Constants.ETH_DECIMALS; } else { // prettier-ignore ( /* roundId */, rate, /* uint256 startedAt */, /* updatedAt */, /* answeredInRound */ ) = ethStorage.rateOracle.latestRoundData(); require(rate > 0, "Invalid rate"); // No overflow, restricted on storage rateDecimals = int256(10**ethStorage.rateDecimalPlaces); if (ethStorage.mustInvert) { rate = rateDecimals.mul(rateDecimals).div(rate); } } return ETHRate({ rateDecimals: rateDecimals, rate: rate, buffer: ethStorage.buffer, haircut: ethStorage.haircut, liquidationDiscount: ethStorage.liquidationDiscount }); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; library nTokenCalculations { using Bitmap for bytes32; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using CashGroup for CashGroupParameters; /// @notice Returns the nToken present value denominated in asset terms. function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256) { int256 totalAssetPV; int256 totalUnderlyingPV; { uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken); // If the first asset maturity has passed (the 3 month), this means that all the LTs must // be settled except the 6 month (which is now the 3 month). We don't settle LTs except in // initialize markets so we calculate the cash value of the portfolio here. if (nextSettleTime <= blockTime) { // NOTE: this condition should only be present for a very short amount of time, which is the window between // when the markets are no longer tradable at quarter end and when the new markets have been initialized. // We time travel back to one second before maturity to value the liquidity tokens. Although this value is // not strictly correct the different should be quite slight. We do this to ensure that free collateral checks // for withdraws and liquidations can still be processed. If this condition persists for a long period of time then // the entire protocol will have serious problems as markets will not be tradable. blockTime = nextSettleTime - 1; } } // This is the total value in liquid assets (int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime); // Then get the total value in any idiosyncratic fCash residuals (if they exist) bytes32 ifCashBits = getNTokenifCashBits( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); int256 ifCashResidualUnderlyingPV = 0; if (ifCashBits != 0) { // Non idiosyncratic residuals have already been accounted for (ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, false, // nToken present value calculation does not use risk adjusted values ifCashBits ); } // Return the total present value denominated in asset terms return totalAssetValueInMarkets .add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV)) .add(nToken.cashBalance); } /** * @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts * in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken * portfolio. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to * the account's share of the total supply * @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually * withdrawn from markets */ function _getProportionalLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem ) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; tokensToWithdraw = new int256[](numMarkets); netfCash = new int256[](numMarkets); for (uint256 i = 0; i < numMarkets; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply); } } /** * @notice Returns the number of liquidity tokens to withdraw from each market if the nToken * has idiosyncratic residuals during nToken redeem. In this case the redeemer will take * their cash from the rest of the fCash markets, redeeming around the nToken. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param blockTime block time * @param ifCashBits the bits in the bitmap that represent ifCash assets * @return tokensToWithdraw array of tokens to withdraw from each corresponding market * @return netfCash array of netfCash amounts to go back to the account */ function getLiquidityTokenWithdraw( nTokenPortfolio memory nToken, int256 nTokensToRedeem, uint256 blockTime, bytes32 ifCashBits ) internal view returns (int256[] memory, int256[] memory) { // If there are no ifCash bits set then this will just return the proportion of all liquidity tokens if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem); ( int256 totalAssetValueInMarkets, int256[] memory netfCash ) = getNTokenMarketValue(nToken, blockTime); int256[] memory tokensToWithdraw = new int256[](netfCash.length); // NOTE: this total portfolio asset value does not include any cash balance the nToken may hold. // The redeemer will always get a proportional share of this cash balance and therefore we don't // need to account for it here when we calculate the share of liquidity tokens to withdraw. We are // only concerned with the nToken's portfolio assets in this method. int256 totalPortfolioAssetValue; { // Returns the risk adjusted net present value for the idiosyncratic residuals (int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, true, // use risk adjusted here to assess a penalty for withdrawing around the residual ifCashBits ); // NOTE: we do not include cash balance here because the account will always take their share // of the cash balance regardless of the residuals totalPortfolioAssetValue = totalAssetValueInMarkets.add( nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV) ); } // Loops through each liquidity token and calculates how much the redeemer can withdraw to get // the requisite amount of present value after adjusting for the ifCash residual value that is // not accessible via redemption. for (uint256 i = 0; i < tokensToWithdraw.length; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; // Redeemer's baseline share of the liquidity tokens based on total supply: // redeemerShare = totalTokens * nTokensToRedeem / totalSupply // Scalar factor to account for residual value (need to inflate the tokens to withdraw // proportional to the value locked up in ifCash residuals): // scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets // Final math equals: // tokensToWithdraw = redeemerShare * scalarFactor // tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue) // / (totalAssetValueInMarkets * totalSupply) tokensToWithdraw[i] = totalTokens .mul(nTokensToRedeem) .mul(totalPortfolioAssetValue); tokensToWithdraw[i] = tokensToWithdraw[i] .div(totalAssetValueInMarkets) .div(nToken.totalSupply); // This is the share of net fcash that will be credited back to the account netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens); } return (tokensToWithdraw, netfCash); } /// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by /// the liquidity tokens held in each market and their corresponding fCash positions. The formula /// can be described as: /// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash)) /// where netfCash = fCashClaim + fCash /// and fCash refers the the fCash position at the corresponding maturity function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256 totalAssetValue, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; netfCash = new int256[](numMarkets); MarketParameters memory market; for (uint256 i = 0; i < numMarkets; i++) { // Load the corresponding market into memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i]; uint256 maturity = liquidityToken.maturity; // Get the fCash claims and fCash assets. We do not use haircut versions here because // nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied // at the end of the calculation to the entire PV instead). (int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market); // fCash is denominated in underlying netfCash[i] = fCashClaim.add( BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, maturity ) ); // This calculates for a single liquidity token: // assetCashClaim + convertToAssetCash(pv(netfCash)) int256 netAssetValueInMarket = assetCashClaim.add( nToken.cashGroup.assetRate.convertFromUnderlying( AssetHandler.getPresentfCashValue( netfCash[i], maturity, blockTime, // No need to call cash group for oracle rate, it is up to date here // and we are assured to be referring to this market. market.oracleRate ) ) ); // Calculate the running total totalAssetValue = totalAssetValue.add(netAssetValueInMarket); } } /// @notice Returns just the bits in a bitmap that are idiosyncratic function getNTokenifCashBits( address tokenAddress, uint256 currencyId, uint256 lastInitializedTime, uint256 blockTime, uint256 maxMarketIndex ) internal view returns (bytes32) { // If max market index is less than or equal to 2, there are never ifCash assets by construction if (maxMarketIndex <= 2) return bytes32(0); bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId); // Handles the case when there are no assets at the first initialization if (assetsBitmap == 0) return assetsBitmap; uint256 tRef = DateTime.getReferenceTime(blockTime); if (tRef == lastInitializedTime) { // This is a more efficient way to turn off ifCash assets in the common case when the market is // initialized immediately return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK); } else { // In this branch, initialize markets has occurred past the time above. It would occur in these // two scenarios (both should be exceedingly rare): // 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef) // 2. somehow initialize markets has been delayed for more than 24 hours for (uint i = 1; i <= maxMarketIndex; i++) { // In this loop we get the maturity of each active market and turn off the corresponding bit // one by one. It is less efficient than the option above. uint256 maturity = tRef + DateTime.getTradedMarket(i); (uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity); assetsBitmap = assetsBitmap.setBit(bitNum, false); } return assetsBitmap; } } }
Calculate binary exponent of x. Revert on overflow. x signed 64.64-bit fixed point number return signed 64.64-bit fixed point number/
function exp_2 (int128 x) internal pure returns (int128) { uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); }
12,596
pragma solidity ^0.6.12; abstract contract context10 { //inject NONSTANDARD NAMING function _MSGSENDER9() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA1() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface ierc202 { //inject NONSTANDARD NAMING function TOTALSUPPLY1() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address ACCOUNT10) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE1(address OWNER0, address SPENDER5) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE1(address SPENDER5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER2(address indexed FROM2, address indexed TO9, uint256 VALUE2); //inject NONSTANDARD NAMING event APPROVAL10(address indexed OWNER0, address indexed SPENDER5, uint256 VALUE2); //inject NONSTANDARD NAMING } library safemath1 { //inject NONSTANDARD NAMING function ADD4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 C8 = A1 + B6; //inject NONSTANDARD NAMING require(C8 >= A1, "SafeMath: addition overflow"); return C8; } function SUB5(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB5(A1, B6, "SafeMath: subtraction overflow"); } function SUB5(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B6 <= A1, ERRORMESSAGE3); uint256 C8 = A1 - B6; //inject NONSTANDARD NAMING return C8; } function MUL6(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (A1 == 0) { return 0; } uint256 C8 = A1 * B6; //inject NONSTANDARD NAMING require(C8 / A1 == B6, "SafeMath: multiplication overflow"); return C8; } function DIV4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV4(A1, B6, "SafeMath: division by zero"); } function DIV4(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B6 > 0, ERRORMESSAGE3); uint256 C8 = A1 / B6; //inject NONSTANDARD NAMING // assert(a == b * c + a % b); // There is no case in which this doesn't hold return C8; } function MOD8(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD8(A1, B6, "SafeMath: modulo by zero"); } function MOD8(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B6 != 0, ERRORMESSAGE3); return A1 % B6; } } library address5 { //inject NONSTANDARD NAMING function ISCONTRACT2(address ACCOUNT10) internal view returns (bool) { //inject NONSTANDARD NAMING // 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 CODEHASH4; //inject NONSTANDARD NAMING bytes32 ACCOUNTHASH1 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING // solhint-disable-next-line no-inline-assembly assembly { CODEHASH4 := extcodehash(ACCOUNT10) } return (CODEHASH4 != ACCOUNTHASH1 && CODEHASH4 != 0x0); } function SENDVALUE0(address payable RECIPIENT5, uint256 AMOUNT9) internal { //inject NONSTANDARD NAMING require(address(this).balance >= AMOUNT9, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool SUCCESS3, ) = RECIPIENT5.call{ value: AMOUNT9 }(""); //inject NONSTANDARD NAMING require(SUCCESS3, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL5(address TARGET4, bytes memory DATA2) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL5(TARGET4, DATA2, "Address: low-level call failed"); } function FUNCTIONCALL5(address TARGET4, bytes memory DATA2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, 0, ERRORMESSAGE3); } function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE5(TARGET4, DATA2, VALUE2, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= VALUE2, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, VALUE2, ERRORMESSAGE3); } function _FUNCTIONCALLWITHVALUE9(address TARGET4, bytes memory DATA2, uint256 WEIVALUE7, string memory ERRORMESSAGE3) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT2(TARGET4), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool SUCCESS3, bytes memory RETURNDATA9) = TARGET4.call{ value: WEIVALUE7 }(DATA2); //inject NONSTANDARD NAMING if (SUCCESS3) { return RETURNDATA9; } else { // Look for revert reason and bubble it up if present if (RETURNDATA9.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(RETURNDATA9) revert(add(32, RETURNDATA9), returndata_size) } } else { revert(ERRORMESSAGE3); } } } } library safeerc206 { //inject NONSTANDARD NAMING using safemath1 for uint256; using address5 for address; function SAFETRANSFER10(ierc202 TOKEN0, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFER5.selector, TO9, VALUE2)); } function SAFETRANSFERFROM2(ierc202 TOKEN0, address FROM2, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFERFROM10.selector, FROM2, TO9, VALUE2)); } function SAFEAPPROVE2(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING // 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((VALUE2 == 0) || (TOKEN0.ALLOWANCE1(address(this), SPENDER5) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, VALUE2)); } function SAFEINCREASEALLOWANCE0(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).ADD4(VALUE2); //inject NONSTANDARD NAMING _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4)); } function SAFEDECREASEALLOWANCE7(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).SUB5(VALUE2, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4)); } function _CALLOPTIONALRETURN7(ierc202 TOKEN0, bytes memory DATA2) private { //inject NONSTANDARD NAMING // 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 RETURNDATA9 = address(TOKEN0).FUNCTIONCALL5(DATA2, "SafeERC20: low-level call failed"); //inject NONSTANDARD NAMING if (RETURNDATA9.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(RETURNDATA9, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ownable2 is context10 { //inject NONSTANDARD NAMING address private _OWNER5; //inject NONSTANDARD NAMING event OWNERSHIPTRANSFERRED2(address indexed PREVIOUSOWNER0, address indexed NEWOWNER9); //inject NONSTANDARD NAMING constructor () internal { address MSGSENDER1 = _MSGSENDER9(); //inject NONSTANDARD NAMING _OWNER5 = MSGSENDER1; emit OWNERSHIPTRANSFERRED2(address(0), MSGSENDER1); } function OWNER2() public view returns (address) { //inject NONSTANDARD NAMING return _OWNER5; } modifier ONLYOWNER10() { //inject NONSTANDARD NAMING require(_OWNER5 == _MSGSENDER9(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP2() public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED2(_OWNER5, address(0)); _OWNER5 = address(0); } function TRANSFEROWNERSHIP5(address NEWOWNER9) public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING require(NEWOWNER9 != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED2(_OWNER5, NEWOWNER9); _OWNER5 = NEWOWNER9; } } contract erc206 is context10, ierc202 { //inject NONSTANDARD NAMING using safemath1 for uint256; using address5 for address; mapping (address => uint256) private _BALANCES2; //inject NONSTANDARD NAMING mapping (address => mapping (address => uint256)) private _ALLOWANCES8; //inject NONSTANDARD NAMING uint256 private _TOTALSUPPLY10; //inject NONSTANDARD NAMING string private _NAME6; //inject NONSTANDARD NAMING string private _SYMBOL5; //inject NONSTANDARD NAMING uint8 private _DECIMALS1; //inject NONSTANDARD NAMING constructor (string memory NAME8, string memory SYMBOL9) public { //inject NONSTANDARD NAMING _NAME6 = NAME8; _SYMBOL5 = SYMBOL9; _DECIMALS1 = 18; } function NAME2() public view returns (string memory) { //inject NONSTANDARD NAMING return _NAME6; } function SYMBOL4() public view returns (string memory) { //inject NONSTANDARD NAMING return _SYMBOL5; } function DECIMALS0() public view returns (uint8) { //inject NONSTANDARD NAMING return _DECIMALS1; } function TOTALSUPPLY1() public view override returns (uint256) { //inject NONSTANDARD NAMING return _TOTALSUPPLY10; } function BALANCEOF3(address ACCOUNT10) public view override returns (uint256) { //inject NONSTANDARD NAMING return _BALANCES2[ACCOUNT10]; } function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER10(_MSGSENDER9(), RECIPIENT5, AMOUNT9); return true; } function ALLOWANCE1(address OWNER0, address SPENDER5) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _ALLOWANCES8[OWNER0][SPENDER5]; } function APPROVE1(address SPENDER5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE0(_MSGSENDER9(), SPENDER5, AMOUNT9); return true; } function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER10(SENDER1, RECIPIENT5, AMOUNT9); _APPROVE0(SENDER1, _MSGSENDER9(), _ALLOWANCES8[SENDER1][_MSGSENDER9()].SUB5(AMOUNT9, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE2(address SPENDER5, uint256 ADDEDVALUE8) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].ADD4(ADDEDVALUE8)); return true; } function DECREASEALLOWANCE5(address SPENDER5, uint256 SUBTRACTEDVALUE10) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].SUB5(SUBTRACTEDVALUE10, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING require(SENDER1 != address(0), "ERC20: transfer from the zero address"); require(RECIPIENT5 != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER8(SENDER1, RECIPIENT5, AMOUNT9); _BALANCES2[SENDER1] = _BALANCES2[SENDER1].SUB5(AMOUNT9, "ERC20: transfer amount exceeds balance"); _BALANCES2[RECIPIENT5] = _BALANCES2[RECIPIENT5].ADD4(AMOUNT9); emit TRANSFER2(SENDER1, RECIPIENT5, AMOUNT9); } function _MINT10(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING require(ACCOUNT10 != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER8(address(0), ACCOUNT10, AMOUNT9); _TOTALSUPPLY10 = _TOTALSUPPLY10.ADD4(AMOUNT9); _BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].ADD4(AMOUNT9); emit TRANSFER2(address(0), ACCOUNT10, AMOUNT9); } function _BURN5(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING require(ACCOUNT10 != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER8(ACCOUNT10, address(0), AMOUNT9); _BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].SUB5(AMOUNT9, "ERC20: burn amount exceeds balance"); _TOTALSUPPLY10 = _TOTALSUPPLY10.SUB5(AMOUNT9); emit TRANSFER2(ACCOUNT10, address(0), AMOUNT9); } function _APPROVE0(address OWNER0, address SPENDER5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING require(OWNER0 != address(0), "ERC20: approve from the zero address"); require(SPENDER5 != address(0), "ERC20: approve to the zero address"); _ALLOWANCES8[OWNER0][SPENDER5] = AMOUNT9; emit APPROVAL10(OWNER0, SPENDER5, AMOUNT9); } function _SETUPDECIMALS6(uint8 DECIMALS_1) internal { //inject NONSTANDARD NAMING _DECIMALS1 = DECIMALS_1; } function _BEFORETOKENTRANSFER8(address FROM2, address TO9, uint256 AMOUNT9) internal virtual { } //inject NONSTANDARD NAMING } // Moon Token with Governance. contract moontoken3 is erc206("MOON.finance", "MOON"), ownable2 { //inject NONSTANDARD NAMING function MINT7(address _TO2, uint256 _AMOUNT3) public ONLYOWNER10 { //inject NONSTANDARD NAMING _MINT10(_TO2, _AMOUNT3); } }
inject NONSTANDARD NAMING
function DIV4(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) {
13,119,582
./full_match/1/0x38D8FA043913e8Ef6466d01BEF4Af42Cafa3b235/sources/contracts/factories/DelegatedManagerFactory.sol
Because we validate uniqueness of _extensions only one transaction can be sent to each extension during this transaction. Due to this no extension can be used for any SetToken transactions other than initializing these contracts Stores temporary creation metadata during the contract creation step. Data is retrieved, read and finally deleted during `initialize`. _setToken Instance of SetToken _manager Address of DelegatedManager created for SetToken _owner Address that will be given the `owner` DelegatedManager's role on initialization _methodologist Address that will be given the `methodologist` DelegatedManager's role on initialization/
extension.functionCallWithValue(initializeBytecode, 0); } } function _setInitializationState( ISetToken _setToken, address _manager, address _owner, address _methodologist ) internal { initializeState[_setToken] = InitializeParams({ deployer: msg.sender, owner: _owner, methodologist: _methodologist, manager: IDelegatedManager(_manager), isPending: true }); }
3,150,710
./partial_match/56/0xba3141Aba8247Bb46d6f1a15770df227de2dF5e5/sources/ErnteSwapBEP20.sol
this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint256 amount0, uint256 amount1) { uint256 balance0 = IBEP20(_token0).balanceOf(address(this)); uint256 balance1 = IBEP20(_token1).balanceOf(address(this)); uint256 liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); require(amount0 > 0 && amount1 > 0, 'ErnteSwapPair: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IBEP20(_token0).balanceOf(address(this)); balance1 = IBEP20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); emit Burn(msg.sender, amount0, amount1, to); }
11,059,578
./full_match/3/0x7A772f6b56154f53516B7D5Fbb10A385e0C09a0A/sources/browser/C2.sol
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint the amount of tokens to be transferred/ Check is not needed because sub(_allowance, _value) will already throw if this condition is not met if (_value > _allowance) throw;
function transferFrom(address _from, address _to, uint _value) public virtual override onlyPayloadSize(3 * 32) { uint _allowance = allowed[_from][msg.sender]; uint256 fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(_from, owner, fee); } emit Transfer(_from, _to, sendAmount); }
8,150,833
./full_match/4/0xA02d6BEADD415e26a0e5D14ca5c8A3e660840731/sources/contracts/Proxy.sol
Upgrade to an address
function upgradeTo(address impl) public onlyOwner { require(impl != address(0), "Cannot upgrade to invalid address"); require(impl != _implementation, "Cannot upgrade to the same implementation"); _implementation = impl; emit Upgraded(impl); }
12,327,463
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {DSMath} from "../vendor/DSMath.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {VaultLifecycle} from "./VaultLifecycle.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Vault} from "./Vault.sol"; import {ShareMath} from "./ShareMath.sol"; import {ISTETH, IWSTETH} from "../interfaces/ISTETH.sol"; import {IWETH} from "../interfaces/IWETH.sol"; import {ICRV} from "../interfaces/ICRV.sol"; import {IStrikeSelection} from "../interfaces/IRibbon.sol"; import { IOtokenFactory, IOtoken, IController, GammaTypes } from "../interfaces/GammaInterface.sol"; import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol"; import {IOptionsPremiumPricer} from "../interfaces/IRibbon.sol"; library VaultLifecycleSTETH { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @notice Sets the next option the vault will be shorting, and calculates its premium for the auction * @param closeParams is the struct with details on previous option and strike selection details * @param vaultParams is the struct with vault general data * @param vaultState is the struct with vault accounting state * @param collateralAsset is the address of the collateral asset * @return otokenAddress is the address of the new option * @return premium is the premium of the new option * @return strikePrice is the strike price of the new option * @return delta is the delta of the new option */ function commitAndClose( VaultLifecycle.CloseParams calldata closeParams, Vault.VaultParams storage vaultParams, Vault.VaultState storage vaultState, address collateralAsset ) external returns ( address otokenAddress, uint256 premium, uint256 strikePrice, uint256 delta ) { uint256 expiry = VaultLifecycle.getNextExpiry(closeParams.currentOption); IStrikeSelection selection = IStrikeSelection(closeParams.strikeSelection); // calculate strike and delta (strikePrice, delta) = closeParams.lastStrikeOverrideRound == vaultState.round ? (closeParams.overriddenStrikePrice, selection.delta()) : selection.getStrikePrice(expiry, false); require(strikePrice != 0, "!strikePrice"); // retrieve address if option already exists, or deploy it otokenAddress = VaultLifecycle.getOrDeployOtoken( closeParams, vaultParams, vaultParams.underlying, collateralAsset, strikePrice, expiry, false ); premium = _getOTokenPremium( otokenAddress, closeParams.optionsPremiumPricer, closeParams.premiumDiscount, collateralAsset ); return (otokenAddress, premium, strikePrice, delta); } /** * @notice Calculate the shares to mint, new price per share, and amount of funds to re-allocate as collateral for the new round * @param currentShareSupply is the total supply of shares * @param currentBalance is the total balance of the vault * @param vaultParams is the struct with vault general data * @param vaultState is the struct with vault accounting state * @return newLockedAmount is the amount of funds to allocate for the new round * @return queuedWithdrawAmount is the amount of funds set aside for withdrawal * @return newPricePerShare is the price per share of the new round * @return mintShares is the amount of shares to mint from deposits */ function rollover( uint256 currentShareSupply, uint256 currentBalance, Vault.VaultParams calldata vaultParams, Vault.VaultState calldata vaultState ) external pure returns ( uint256 newLockedAmount, uint256 queuedWithdrawAmount, uint256 newPricePerShare, uint256 mintShares ) { uint256 pendingAmount = uint256(vaultState.totalPending); uint256 _decimals = vaultParams.decimals; newPricePerShare = ShareMath.pricePerShare( currentShareSupply, currentBalance, pendingAmount, _decimals ); // After closing the short, if the options expire in-the-money // vault pricePerShare would go down because vault's asset balance decreased. // This ensures that the newly-minted shares do not take on the loss. uint256 _mintShares = ShareMath.assetToShares(pendingAmount, newPricePerShare, _decimals); uint256 newSupply = currentShareSupply.add(_mintShares); uint256 queuedAmount = newSupply > 0 ? ShareMath.sharesToAsset( vaultState.queuedWithdrawShares, newPricePerShare, _decimals ) : 0; return ( currentBalance.sub(queuedAmount), queuedAmount, newPricePerShare, _mintShares ); } /** * @notice Creates the actual Opyn short position by depositing collateral and minting otokens * @param gammaController is the address of the opyn controller contract * @param marginPool is the address of the opyn margin contract which holds the collateral * @param oTokenAddress is the address of the otoken to mint * @param depositAmount is the amount of collateral to deposit * @return the otoken mint amount */ function createShort( address gammaController, address marginPool, address oTokenAddress, uint256 depositAmount ) external returns (uint256) { IController controller = IController(gammaController); uint256 newVaultID = (controller.getAccountVaultCounter(address(this))).add(1); // An otoken's collateralAsset is the vault's `asset` // So in the context of performing Opyn short operations we call them collateralAsset IOtoken oToken = IOtoken(oTokenAddress); address collateralAsset = oToken.collateralAsset(); uint256 collateralDecimals = uint256(IERC20Detailed(collateralAsset).decimals()); uint256 mintAmount; mintAmount = depositAmount; if (collateralDecimals > 8) { uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals if (mintAmount > scaleBy) { mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8 } } IERC20 collateralToken = IERC20(collateralAsset); collateralToken.safeApprove(marginPool, depositAmount); IController.ActionArgs[] memory actions = new IController.ActionArgs[](3); actions[0] = IController.ActionArgs( IController.ActionType.OpenVault, address(this), // owner address(this), // receiver address(0), // asset, otoken newVaultID, // vaultId 0, // amount 0, //index "" //data ); actions[1] = IController.ActionArgs( IController.ActionType.DepositCollateral, address(this), // owner address(this), // address to transfer from collateralAsset, // deposited asset newVaultID, // vaultId depositAmount, // amount 0, //index "" //data ); actions[2] = IController.ActionArgs( IController.ActionType.MintShortOption, address(this), // owner address(this), // address to transfer to oTokenAddress, // option address newVaultID, // vaultId mintAmount, // amount 0, //index "" //data ); controller.operate(actions); return mintAmount; } /** * @notice Withdraws stETH + WETH (if necessary) from vault using vault shares * @param collateralToken is the address of the collateral token * @param weth is the WETH address * @param recipient is the recipient * @param amount is the withdraw amount in `asset` * @return withdrawAmount is the withdraw amount in `collateralToken` */ function withdrawYieldAndBaseToken( address collateralToken, address weth, address recipient, uint256 amount ) external returns (uint256) { IWSTETH collateral = IWSTETH(collateralToken); uint256 withdrawAmount = collateral.getWstETHByStETH(amount); uint256 yieldTokenBalance = withdrawYieldToken(collateralToken, recipient, withdrawAmount); // If there is not enough wstETH in the vault, it withdraws as much as possible and // transfers the rest in `asset` if (withdrawAmount > yieldTokenBalance) { withdrawBaseToken( collateralToken, weth, recipient, withdrawAmount, yieldTokenBalance ); } return withdrawAmount; } /** * @notice Withdraws stETH from vault * @param collateralToken is the address of the collateral token * @param recipient is the recipient * @param withdrawAmount is the withdraw amount in terms of yearn tokens * @return yieldTokenBalance is the balance of the yield token */ function withdrawYieldToken( address collateralToken, address recipient, uint256 withdrawAmount ) internal returns (uint256) { IERC20 collateral = IERC20(collateralToken); uint256 yieldTokenBalance = collateral.balanceOf(address(this)); uint256 yieldTokensToWithdraw = DSMath.min(yieldTokenBalance, withdrawAmount); if (yieldTokensToWithdraw > 0) { collateral.safeTransfer(recipient, yieldTokensToWithdraw); } return yieldTokenBalance; } /** * @notice Withdraws `asset` from vault * @param collateralToken is the address of the collateral token * @param weth is the WETH address * @param recipient is the recipient * @param withdrawAmount is the withdraw amount in terms of yearn tokens * @param yieldTokenBalance is the collateral token (stETH) balance of the vault */ function withdrawBaseToken( address collateralToken, address weth, address recipient, uint256 withdrawAmount, uint256 yieldTokenBalance ) internal { uint256 underlyingTokensToWithdraw = IWSTETH(collateralToken).getStETHByWstETH( withdrawAmount.sub(yieldTokenBalance) ); IWETH(weth).deposit{value: underlyingTokensToWithdraw}(); IERC20(weth).safeTransfer(recipient, underlyingTokensToWithdraw); } /** * @notice Unwraps the necessary amount of the wstETH token * and transfers ETH amount to vault * @param amount is the amount of ETH to withdraw * @param wstEth is the address of wstETH * @param stethToken is the address of stETH * @param crvPool is the address of the steth <-> eth pool on curve * @param minETHOut is the minimum eth amount to receive from the swap * @return amountETHOut is the amount of eth unwrapped available for the withdrawal (may incur curve slippage) */ function unwrapYieldToken( uint256 amount, address wstEth, address stethToken, address crvPool, uint256 minETHOut ) external returns (uint256) { require( amount >= minETHOut, "Amount withdrawn smaller than minETHOut from swap" ); require( minETHOut.mul(10**18).div(amount) >= 0.95 ether, "Slippage on minETHOut too high" ); uint256 ethBalance = address(this).balance; IERC20 steth = IERC20(stethToken); uint256 stethBalance = steth.balanceOf(address(this)); // 3 different success scenarios // Scenario 1. We hold enough ETH to satisfy withdrawal. Send it out directly // Scenario 2. We hold enough wstETH to satisy withdrawal. Unwrap then swap // Scenario 3. We hold enough ETH + stETH to satisfy withdrawal. Do a swap // Scenario 1 if (ethBalance >= amount) { return amount; } // Scenario 2 stethBalance = unwrapWstethForWithdrawal( wstEth, steth, ethBalance, stethBalance, amount, minETHOut ); // Scenario 3 // Now that we satisfied the ETH + stETH sum, we swap the stETH amounts necessary // to facilitate a withdrawal // This won't underflow since we already asserted that ethBalance < amount before this uint256 stEthAmountToSwap = DSMath.min(amount.sub(ethBalance), stethBalance); uint256 ethAmountOutFromSwap = swapStEthToEth(steth, crvPool, stEthAmountToSwap); uint256 totalETHOut = ethBalance.add(ethAmountOutFromSwap); // Since minETHOut is derived from calling the Curve pool's getter, // it reverts in the worst case where the user needs to unwrap and sell // 100% of their ETH withdrawal amount require( totalETHOut >= minETHOut, "Output ETH amount smaller than minETHOut" ); return totalETHOut; } /** * @notice Unwraps the required amount of wstETH to a target ETH amount * @param wstEthAddress is the address for wstETH * @param steth is the ERC20 of stETH * @param startStEthBalance is the starting stETH balance used to determine how much more to unwrap * @param ethAmount is the ETH amount needed for the contract * @param minETHOut is the ETH amount but adjusted for slippage * @return the new stETH balance */ function unwrapWstethForWithdrawal( address wstEthAddress, IERC20 steth, uint256 ethBalance, uint256 startStEthBalance, uint256 ethAmount, uint256 minETHOut ) internal returns (uint256) { uint256 ethstEthSum = ethBalance.add(startStEthBalance); if (ethstEthSum < minETHOut) { uint256 stethNeededFromUnwrap = ethAmount.sub(ethstEthSum); IWSTETH wstEth = IWSTETH(wstEthAddress); uint256 wstAmountToUnwrap = wstEth.getWstETHByStETH(stethNeededFromUnwrap); wstEth.unwrap(wstAmountToUnwrap); uint256 newStEthBalance = steth.balanceOf(address(this)); require( ethBalance.add(newStEthBalance) >= minETHOut, "Unwrapping wstETH did not return sufficient stETH" ); return newStEthBalance; } return startStEthBalance; } /** * @notice Swaps from stEth to ETH on the Lido Curve pool * @param steth is the address for the Lido staked ether * @param crvPool is the Curve pool address to do the swap * @param stEthAmount is the stEth amount to be swapped to Ether * @return ethAmountOutFromSwap is the returned ETH amount from swap */ function swapStEthToEth( IERC20 steth, address crvPool, uint256 stEthAmount ) internal returns (uint256) { steth.safeApprove(crvPool, stEthAmount); // CRV SWAP HERE from steth -> eth // 0 = ETH, 1 = STETH // We are setting 1, which is the smallest possible value for the _minAmountOut parameter // However it is fine because we check that the totalETHOut >= minETHOut at the end // which makes sandwich attacks not possible uint256 ethAmountOutFromSwap = ICRV(crvPool).exchange(1, 0, stEthAmount, 1); return ethAmountOutFromSwap; } /** * @notice Wraps the necessary amount of the base token to the yield-bearing yearn token * @param weth is the address of weth * @param collateralToken is the address of the collateral token */ function wrapToYieldToken( address weth, address collateralToken, address steth ) external { // Unwrap all weth premiums transferred to contract IWETH wethToken = IWETH(weth); uint256 wethBalance = wethToken.balanceOf(address(this)); if (wethBalance > 0) { wethToken.withdraw(wethBalance); } uint256 ethBalance = address(this).balance; IWSTETH collateral = IWSTETH(collateralToken); IERC20 stethToken = IERC20(steth); if (ethBalance > 0) { // Send eth to Lido, recieve steth ISTETH(steth).submit{value: ethBalance}(address(this)); } // Get all steth in contract uint256 stethBalance = stethToken.balanceOf(address(this)); if (stethBalance > 0) { // approve wrap stethToken.safeApprove(collateralToken, stethBalance.add(1)); // Wrap to wstETH - need to add 1 to steth balance as it is innacurate collateral.wrap(stethBalance.add(1)); } } /** * @notice Gets stETH for direct stETH withdrawals, converts wstETH/ETH to stETH if not enough stETH * @param steth is the address of steth * @param wstEth is the address of wsteth * @param amount is the amount to withdraw * @return amount of stETH to transfer to the user, this is to account for rounding errors when unwrapping wstETH */ function withdrawStEth( address steth, address wstEth, uint256 amount ) external returns (uint256) { // 3 different scenarios for withdrawing stETH directly // Scenario 1. We hold enough stETH to satisfy withdrawal. Send it out directly // Scenario 2. We hold enough stETH + wstETH to satisy withdrawal. Unwrap wstETH then send it // Scenario 3. We hold enough stETH + wstETH + ETH satisfy withdrawal. Unwrap wstETH, wrap ETH then send it uint256 _amount = amount; uint256 stethBalance = IERC20(steth).balanceOf(address(this)); if (stethBalance >= amount) { // Can send out the stETH directly return amount; // We return here if we have enough stETH to satisfy the withdrawal } else { // If amount > stethBalance, send out the entire stethBalance and check wstETH and ETH amount = amount.sub(stethBalance); } uint256 wstethBalance = IWSTETH(wstEth).balanceOf(address(this)); uint256 totalShares = ISTETH(steth).getTotalShares(); uint256 totalPooledEther = ISTETH(steth).getTotalPooledEther(); stethBalance = wstethBalance.mul(totalPooledEther).div(totalShares); if (stethBalance >= amount) { wstethBalance = amount.mul(totalShares).div(totalPooledEther); // Avoids reverting if unwrap amount is 0 if (wstethBalance > 0) { // Unwraps wstETH and sends out the received stETH directly IWSTETH(wstEth).unwrap(wstethBalance); // Accounts for rounding errors when unwrapping wstETH, this is safe because this function would've // returned already if the stETH balance was greater than our withdrawal amount return IERC20(steth).balanceOf(address(this)); // We return here if we have enough stETH + wstETH } } else if (stethBalance > 0) { stethBalance = IERC20(steth).balanceOf(address(this)); IWSTETH(wstEth).unwrap(wstethBalance); // Accounts for rounding errors when unwrapping wstETH amount = amount.sub( IERC20(steth).balanceOf(address(this)).sub(stethBalance) ); } // Wrap ETH to stETH if we don't have enough stETH + wstETH uint256 ethBalance = address(this).balance; if (amount > 0 && ethBalance >= amount) { ISTETH(steth).submit{value: amount}(address(this)); } else if (ethBalance > 0) { ISTETH(steth).submit{value: ethBalance}(address(this)); } stethBalance = IERC20(steth).balanceOf(address(this)); // Accounts for rounding errors by a margin of 3 wei require(_amount.add(3) >= stethBalance, "Unwrapped too much stETH"); require(_amount <= stethBalance.add(3), "Unwrapped insufficient stETH"); return stethBalance; // We return here if we have enough stETH + wstETH + ETH } /** * @notice Helper function to make either an ETH transfer or ERC20 transfer * @param recipient is the receiving address * @param amount is the transfer amount */ function transferAsset(address recipient, uint256 amount) public { (bool success, ) = payable(recipient).call{value: amount}(""); require(success, "!success"); } function getOTokenPremium( address oTokenAddress, address optionsPremiumPricer, uint256 premiumDiscount, address collateralToken ) external view returns (uint256) { return _getOTokenPremium( oTokenAddress, optionsPremiumPricer, premiumDiscount, collateralToken ); } function _getOTokenPremium( address oTokenAddress, address optionsPremiumPricer, uint256 premiumDiscount, address collateralToken ) internal view returns (uint256) { IOtoken newOToken = IOtoken(oTokenAddress); IOptionsPremiumPricer premiumPricer = IOptionsPremiumPricer(optionsPremiumPricer); // Apply black-scholes formula (from rvol library) to option given its features // and get price for 100 contracts denominated in the underlying asset for call option // and USDC for put option uint256 optionPremium = premiumPricer.getPremium( newOToken.strikePrice(), newOToken.expiryTimestamp(), newOToken.isPut() ); // Apply a discount to incentivize arbitraguers optionPremium = optionPremium.mul(premiumDiscount).div( 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER ); // get the black scholes premium of the option and adjust premium based on // steth <-> eth exchange rate uint256 adjustedPremium = DSMath.wmul( optionPremium, IWSTETH(collateralToken).stEthPerToken() ); require( adjustedPremium <= type(uint96).max, "adjustedPremium > type(uint96) max value!" ); require(adjustedPremium > 0, "!adjustedPremium"); return adjustedPremium; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT /// math.sol -- mixin for inline numerical wizardry // 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.4.13; library DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; //rounds to zero if x*y < WAD / 2 function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Vault} from "./Vault.sol"; import {ShareMath} from "./ShareMath.sol"; import {IStrikeSelection} from "../interfaces/IRibbon.sol"; import {GnosisAuction} from "./GnosisAuction.sol"; import { IOtokenFactory, IOtoken, IController, GammaTypes } from "../interfaces/GammaInterface.sol"; import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol"; import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol"; import {IOptionsPurchaseQueue} from "../interfaces/IOptionsPurchaseQueue.sol"; import {SupportsNonCompliantERC20} from "./SupportsNonCompliantERC20.sol"; import {IOptionsPremiumPricer} from "../interfaces/IRibbon.sol"; library VaultLifecycle { using SafeMath for uint256; using SupportsNonCompliantERC20 for IERC20; struct CloseParams { address OTOKEN_FACTORY; address USDC; address currentOption; uint256 delay; uint16 lastStrikeOverrideRound; uint256 overriddenStrikePrice; address strikeSelection; address optionsPremiumPricer; uint256 premiumDiscount; } /// @notice Default maximum option allocation for the queue (50%) uint256 internal constant QUEUE_OPTION_ALLOCATION = 5000; /** * @notice Sets the next option the vault will be shorting, and calculates its premium for the auction * @param closeParams is the struct with details on previous option and strike selection details * @param vaultParams is the struct with vault general data * @param vaultState is the struct with vault accounting state * @return otokenAddress is the address of the new option * @return premium is the premium of the new option * @return strikePrice is the strike price of the new option * @return delta is the delta of the new option */ function commitAndClose( CloseParams calldata closeParams, Vault.VaultParams storage vaultParams, Vault.VaultState storage vaultState ) external returns ( address otokenAddress, uint256 premium, uint256 strikePrice, uint256 delta ) { uint256 expiry = getNextExpiry(closeParams.currentOption); IStrikeSelection selection = IStrikeSelection(closeParams.strikeSelection); bool isPut = vaultParams.isPut; address underlying = vaultParams.underlying; address asset = vaultParams.asset; (strikePrice, delta) = closeParams.lastStrikeOverrideRound == vaultState.round ? (closeParams.overriddenStrikePrice, selection.delta()) : selection.getStrikePrice(expiry, isPut); require(strikePrice != 0, "!strikePrice"); // retrieve address if option already exists, or deploy it otokenAddress = getOrDeployOtoken( closeParams, vaultParams, underlying, asset, strikePrice, expiry, isPut ); // get the black scholes premium of the option premium = _getOTokenPremium( otokenAddress, closeParams.optionsPremiumPricer, closeParams.premiumDiscount ); require(premium > 0, "!premium"); return (otokenAddress, premium, strikePrice, delta); } /** * @notice Verify the otoken has the correct parameters to prevent vulnerability to opyn contract changes * @param otokenAddress is the address of the otoken * @param vaultParams is the struct with vault general data * @param collateralAsset is the address of the collateral asset * @param USDC is the address of usdc * @param delay is the delay between commitAndClose and rollToNextOption */ function verifyOtoken( address otokenAddress, Vault.VaultParams storage vaultParams, address collateralAsset, address USDC, uint256 delay ) private view { require(otokenAddress != address(0), "!otokenAddress"); IOtoken otoken = IOtoken(otokenAddress); require(otoken.isPut() == vaultParams.isPut, "Type mismatch"); require( otoken.underlyingAsset() == vaultParams.underlying, "Wrong underlyingAsset" ); require( otoken.collateralAsset() == collateralAsset, "Wrong collateralAsset" ); // we just assume all options use USDC as the strike require(otoken.strikeAsset() == USDC, "strikeAsset != USDC"); uint256 readyAt = block.timestamp.add(delay); require(otoken.expiryTimestamp() >= readyAt, "Expiry before delay"); } /** * @param currentShareSupply is the supply of the shares invoked with totalSupply() * @param asset is the address of the vault's asset * @param decimals is the decimals of the asset * @param lastQueuedWithdrawAmount is the amount queued for withdrawals from last round * @param performanceFee is the perf fee percent to charge on premiums * @param managementFee is the management fee percent to charge on the AUM */ struct RolloverParams { uint256 decimals; uint256 totalBalance; uint256 currentShareSupply; uint256 lastQueuedWithdrawAmount; uint256 performanceFee; uint256 managementFee; } /** * @notice Calculate the shares to mint, new price per share, and amount of funds to re-allocate as collateral for the new round * @param vaultState is the storage variable vaultState passed from RibbonVault * @param params is the rollover parameters passed to compute the next state * @return newLockedAmount is the amount of funds to allocate for the new round * @return queuedWithdrawAmount is the amount of funds set aside for withdrawal * @return newPricePerShare is the price per share of the new round * @return mintShares is the amount of shares to mint from deposits * @return performanceFeeInAsset is the performance fee charged by vault * @return totalVaultFee is the total amount of fee charged by vault */ function rollover( Vault.VaultState storage vaultState, RolloverParams calldata params ) external view returns ( uint256 newLockedAmount, uint256 queuedWithdrawAmount, uint256 newPricePerShare, uint256 mintShares, uint256 performanceFeeInAsset, uint256 totalVaultFee ) { uint256 currentBalance = params.totalBalance; uint256 pendingAmount = vaultState.totalPending; uint256 queuedWithdrawShares = vaultState.queuedWithdrawShares; uint256 balanceForVaultFees; { uint256 pricePerShareBeforeFee = ShareMath.pricePerShare( params.currentShareSupply, currentBalance, pendingAmount, params.decimals ); uint256 queuedWithdrawBeforeFee = params.currentShareSupply > 0 ? ShareMath.sharesToAsset( queuedWithdrawShares, pricePerShareBeforeFee, params.decimals ) : 0; // Deduct the difference between the newly scheduled withdrawals // and the older withdrawals // so we can charge them fees before they leave uint256 withdrawAmountDiff = queuedWithdrawBeforeFee > params.lastQueuedWithdrawAmount ? queuedWithdrawBeforeFee.sub( params.lastQueuedWithdrawAmount ) : 0; balanceForVaultFees = currentBalance .sub(queuedWithdrawBeforeFee) .add(withdrawAmountDiff); } { (performanceFeeInAsset, , totalVaultFee) = VaultLifecycle .getVaultFees( balanceForVaultFees, vaultState.lastLockedAmount, vaultState.totalPending, params.performanceFee, params.managementFee ); } // Take into account the fee // so we can calculate the newPricePerShare currentBalance = currentBalance.sub(totalVaultFee); { newPricePerShare = ShareMath.pricePerShare( params.currentShareSupply, currentBalance, pendingAmount, params.decimals ); // After closing the short, if the options expire in-the-money // vault pricePerShare would go down because vault's asset balance decreased. // This ensures that the newly-minted shares do not take on the loss. mintShares = ShareMath.assetToShares( pendingAmount, newPricePerShare, params.decimals ); uint256 newSupply = params.currentShareSupply.add(mintShares); queuedWithdrawAmount = newSupply > 0 ? ShareMath.sharesToAsset( queuedWithdrawShares, newPricePerShare, params.decimals ) : 0; } return ( currentBalance.sub(queuedWithdrawAmount), // new locked balance subtracts the queued withdrawals queuedWithdrawAmount, newPricePerShare, mintShares, performanceFeeInAsset, totalVaultFee ); } /** * @notice Creates the actual Opyn short position by depositing collateral and minting otokens * @param gammaController is the address of the opyn controller contract * @param marginPool is the address of the opyn margin contract which holds the collateral * @param oTokenAddress is the address of the otoken to mint * @param depositAmount is the amount of collateral to deposit * @return the otoken mint amount */ function createShort( address gammaController, address marginPool, address oTokenAddress, uint256 depositAmount ) external returns (uint256) { IController controller = IController(gammaController); uint256 newVaultID = (controller.getAccountVaultCounter(address(this))).add(1); // An otoken's collateralAsset is the vault's `asset` // So in the context of performing Opyn short operations we call them collateralAsset IOtoken oToken = IOtoken(oTokenAddress); address collateralAsset = oToken.collateralAsset(); uint256 collateralDecimals = uint256(IERC20Detailed(collateralAsset).decimals()); uint256 mintAmount; if (oToken.isPut()) { // For minting puts, there will be instances where the full depositAmount will not be used for minting. // This is because of an issue with precision. // // For ETH put options, we are calculating the mintAmount (10**8 decimals) using // the depositAmount (10**18 decimals), which will result in truncation of decimals when scaling down. // As a result, there will be tiny amounts of dust left behind in the Opyn vault when minting put otokens. // // For simplicity's sake, we do not refund the dust back to the address(this) on minting otokens. // We retain the dust in the vault so the calling contract can withdraw the // actual locked amount + dust at settlement. // // To test this behavior, we can console.log // MarginCalculatorInterface(0x7A48d10f372b3D7c60f6c9770B91398e4ccfd3C7).getExcessCollateral(vault) // to see how much dust (or excess collateral) is left behind. mintAmount = depositAmount .mul(10**Vault.OTOKEN_DECIMALS) .mul(10**18) // we use 10**18 to give extra precision .div(oToken.strikePrice().mul(10**(10 + collateralDecimals))); } else { mintAmount = depositAmount; if (collateralDecimals > 8) { uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals if (mintAmount > scaleBy) { mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8 } } } // double approve to fix non-compliant ERC20s IERC20 collateralToken = IERC20(collateralAsset); collateralToken.safeApproveNonCompliant(marginPool, depositAmount); IController.ActionArgs[] memory actions = new IController.ActionArgs[](3); actions[0] = IController.ActionArgs( IController.ActionType.OpenVault, address(this), // owner address(this), // receiver address(0), // asset, otoken newVaultID, // vaultId 0, // amount 0, //index "" //data ); actions[1] = IController.ActionArgs( IController.ActionType.DepositCollateral, address(this), // owner address(this), // address to transfer from collateralAsset, // deposited asset newVaultID, // vaultId depositAmount, // amount 0, //index "" //data ); actions[2] = IController.ActionArgs( IController.ActionType.MintShortOption, address(this), // owner address(this), // address to transfer to oTokenAddress, // option address newVaultID, // vaultId mintAmount, // amount 0, //index "" //data ); controller.operate(actions); return mintAmount; } /** * @notice Close the existing short otoken position. Currently this implementation is simple. * It closes the most recent vault opened by the contract. This assumes that the contract will * only have a single vault open at any given time. Since calling `_closeShort` deletes vaults by calling SettleVault action, this assumption should hold. * @param gammaController is the address of the opyn controller contract * @return amount of collateral redeemed from the vault */ function settleShort(address gammaController) external returns (uint256) { IController controller = IController(gammaController); // gets the currently active vault ID uint256 vaultID = controller.getAccountVaultCounter(address(this)); GammaTypes.Vault memory vault = controller.getVault(address(this), vaultID); require(vault.shortOtokens.length > 0, "No short"); // An otoken's collateralAsset is the vault's `asset` // So in the context of performing Opyn short operations we call them collateralAsset IERC20 collateralToken = IERC20(vault.collateralAssets[0]); // The short position has been previously closed, or all the otokens have been burned. // So we return early. if (address(collateralToken) == address(0)) { return 0; } // This is equivalent to doing IERC20(vault.asset).balanceOf(address(this)) uint256 startCollateralBalance = collateralToken.balanceOf(address(this)); // If it is after expiry, we need to settle the short position using the normal way // Delete the vault and withdraw all remaining collateral from the vault IController.ActionArgs[] memory actions = new IController.ActionArgs[](1); actions[0] = IController.ActionArgs( IController.ActionType.SettleVault, address(this), // owner address(this), // address to transfer to address(0), // not used vaultID, // vaultId 0, // not used 0, // not used "" // not used ); controller.operate(actions); uint256 endCollateralBalance = collateralToken.balanceOf(address(this)); return endCollateralBalance.sub(startCollateralBalance); } /** * @notice Exercises the ITM option using existing long otoken position. Currently this implementation is simple. * It calls the `Redeem` action to claim the payout. * @param gammaController is the address of the opyn controller contract * @param oldOption is the address of the old option * @param asset is the address of the vault's asset * @return amount of asset received by exercising the option */ function settleLong( address gammaController, address oldOption, address asset ) external returns (uint256) { IController controller = IController(gammaController); uint256 oldOptionBalance = IERC20(oldOption).balanceOf(address(this)); if (controller.getPayout(oldOption, oldOptionBalance) == 0) { return 0; } uint256 startAssetBalance = IERC20(asset).balanceOf(address(this)); // If it is after expiry, we need to redeem the profits IController.ActionArgs[] memory actions = new IController.ActionArgs[](1); actions[0] = IController.ActionArgs( IController.ActionType.Redeem, address(0), // not used address(this), // address to send profits to oldOption, // address of otoken 0, // not used oldOptionBalance, // otoken balance 0, // not used "" // not used ); controller.operate(actions); uint256 endAssetBalance = IERC20(asset).balanceOf(address(this)); return endAssetBalance.sub(startAssetBalance); } /** * @notice Burn the remaining oTokens left over from auction. Currently this implementation is simple. * It burns oTokens from the most recent vault opened by the contract. This assumes that the contract will * only have a single vault open at any given time. * @param gammaController is the address of the opyn controller contract * @param currentOption is the address of the current option * @return amount of collateral redeemed by burning otokens */ function burnOtokens(address gammaController, address currentOption) external returns (uint256) { uint256 numOTokensToBurn = IERC20(currentOption).balanceOf(address(this)); require(numOTokensToBurn > 0, "No oTokens to burn"); IController controller = IController(gammaController); // gets the currently active vault ID uint256 vaultID = controller.getAccountVaultCounter(address(this)); GammaTypes.Vault memory vault = controller.getVault(address(this), vaultID); require(vault.shortOtokens.length > 0, "No short"); IERC20 collateralToken = IERC20(vault.collateralAssets[0]); uint256 startCollateralBalance = collateralToken.balanceOf(address(this)); // Burning `amount` of oTokens from the ribbon vault, // then withdrawing the corresponding collateral amount from the vault IController.ActionArgs[] memory actions = new IController.ActionArgs[](2); actions[0] = IController.ActionArgs( IController.ActionType.BurnShortOption, address(this), // owner address(this), // address to transfer from address(vault.shortOtokens[0]), // otoken address vaultID, // vaultId numOTokensToBurn, // amount 0, //index "" //data ); actions[1] = IController.ActionArgs( IController.ActionType.WithdrawCollateral, address(this), // owner address(this), // address to transfer to address(collateralToken), // withdrawn asset vaultID, // vaultId vault.collateralAmounts[0].mul(numOTokensToBurn).div( vault.shortAmounts[0] ), // amount 0, //index "" //data ); controller.operate(actions); uint256 endCollateralBalance = collateralToken.balanceOf(address(this)); return endCollateralBalance.sub(startCollateralBalance); } /** * @notice Calculates the performance and management fee for this week's round * @param currentBalance is the balance of funds held on the vault after closing short * @param lastLockedAmount is the amount of funds locked from the previous round * @param pendingAmount is the pending deposit amount * @param performanceFeePercent is the performance fee pct. * @param managementFeePercent is the management fee pct. * @return performanceFeeInAsset is the performance fee * @return managementFeeInAsset is the management fee * @return vaultFee is the total fees */ function getVaultFees( uint256 currentBalance, uint256 lastLockedAmount, uint256 pendingAmount, uint256 performanceFeePercent, uint256 managementFeePercent ) internal pure returns ( uint256 performanceFeeInAsset, uint256 managementFeeInAsset, uint256 vaultFee ) { // At the first round, currentBalance=0, pendingAmount>0 // so we just do not charge anything on the first round uint256 lockedBalanceSansPending = currentBalance > pendingAmount ? currentBalance.sub(pendingAmount) : 0; uint256 _performanceFeeInAsset; uint256 _managementFeeInAsset; uint256 _vaultFee; // Take performance fee and management fee ONLY if difference between // last week and this week's vault deposits, taking into account pending // deposits and withdrawals, is positive. If it is negative, last week's // option expired ITM past breakeven, and the vault took a loss so we // do not collect performance fee for last week if (lockedBalanceSansPending > lastLockedAmount) { _performanceFeeInAsset = performanceFeePercent > 0 ? lockedBalanceSansPending .sub(lastLockedAmount) .mul(performanceFeePercent) .div(100 * Vault.FEE_MULTIPLIER) : 0; _managementFeeInAsset = managementFeePercent > 0 ? lockedBalanceSansPending.mul(managementFeePercent).div( 100 * Vault.FEE_MULTIPLIER ) : 0; _vaultFee = _performanceFeeInAsset.add(_managementFeeInAsset); } return (_performanceFeeInAsset, _managementFeeInAsset, _vaultFee); } /** * @notice Either retrieves the option token if it already exists, or deploy it * @param closeParams is the struct with details on previous option and strike selection details * @param vaultParams is the struct with vault general data * @param underlying is the address of the underlying asset of the option * @param collateralAsset is the address of the collateral asset of the option * @param strikePrice is the strike price of the option * @param expiry is the expiry timestamp of the option * @param isPut is whether the option is a put * @return the address of the option */ function getOrDeployOtoken( CloseParams calldata closeParams, Vault.VaultParams storage vaultParams, address underlying, address collateralAsset, uint256 strikePrice, uint256 expiry, bool isPut ) internal returns (address) { IOtokenFactory factory = IOtokenFactory(closeParams.OTOKEN_FACTORY); address otokenFromFactory = factory.getOtoken( underlying, closeParams.USDC, collateralAsset, strikePrice, expiry, isPut ); if (otokenFromFactory != address(0)) { return otokenFromFactory; } address otoken = factory.createOtoken( underlying, closeParams.USDC, collateralAsset, strikePrice, expiry, isPut ); verifyOtoken( otoken, vaultParams, collateralAsset, closeParams.USDC, closeParams.delay ); return otoken; } function getOTokenPremium( address oTokenAddress, address optionsPremiumPricer, uint256 premiumDiscount ) external view returns (uint256) { return _getOTokenPremium( oTokenAddress, optionsPremiumPricer, premiumDiscount ); } function _getOTokenPremium( address oTokenAddress, address optionsPremiumPricer, uint256 premiumDiscount ) internal view returns (uint256) { IOtoken newOToken = IOtoken(oTokenAddress); IOptionsPremiumPricer premiumPricer = IOptionsPremiumPricer(optionsPremiumPricer); // Apply black-scholes formula (from rvol library) to option given its features // and get price for 100 contracts denominated in the underlying asset for call option // and USDC for put option uint256 optionPremium = premiumPricer.getPremium( newOToken.strikePrice(), newOToken.expiryTimestamp(), newOToken.isPut() ); // Apply a discount to incentivize arbitraguers optionPremium = optionPremium.mul(premiumDiscount).div( 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER ); require( optionPremium <= type(uint96).max, "optionPremium > type(uint96) max value!" ); require(optionPremium > 0, "!optionPremium"); return optionPremium; } /** * @notice Starts the gnosis auction * @param auctionDetails is the struct with all the custom parameters of the auction * @return the auction id of the newly created auction */ function startAuction(GnosisAuction.AuctionDetails calldata auctionDetails) external returns (uint256) { return GnosisAuction.startAuction(auctionDetails); } /** * @notice Settles the gnosis auction * @param gnosisEasyAuction is the contract address of Gnosis easy auction protocol * @param auctionID is the auction ID of the gnosis easy auction */ function settleAuction(address gnosisEasyAuction, uint256 auctionID) internal { IGnosisAuction(gnosisEasyAuction).settleAuction(auctionID); } /** * @notice Places a bid in an auction * @param bidDetails is the struct with all the details of the bid including the auction's id and how much to bid */ function placeBid(GnosisAuction.BidDetails calldata bidDetails) external returns ( uint256 sellAmount, uint256 buyAmount, uint64 userId ) { return GnosisAuction.placeBid(bidDetails); } /** * @notice Claims the oTokens belonging to the vault * @param auctionSellOrder is the sell order of the bid * @param gnosisEasyAuction is the address of the gnosis auction contract holding custody to the funds * @param counterpartyThetaVault is the address of the counterparty theta vault of this delta vault */ function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault ) external { GnosisAuction.claimAuctionOtokens( auctionSellOrder, gnosisEasyAuction, counterpartyThetaVault ); } /** * @notice Allocates the vault's minted options to the OptionsPurchaseQueue contract * @dev Skipped if the optionsPurchaseQueue doesn't exist * @param optionsPurchaseQueue is the OptionsPurchaseQueue contract * @param option is the minted option * @param optionsAmount is the amount of options minted * @param optionAllocation is the maximum % of options to allocate towards the purchase queue (will only allocate * up to the amount that is on the queue) * @return allocatedOptions is the amount of options that ended up getting allocated to the OptionsPurchaseQueue */ function allocateOptions( address optionsPurchaseQueue, address option, uint256 optionsAmount, uint256 optionAllocation ) external returns (uint256 allocatedOptions) { // Skip if optionsPurchaseQueue is address(0) if (optionsPurchaseQueue != address(0)) { allocatedOptions = optionsAmount.mul(optionAllocation).div( 100 * Vault.OPTION_ALLOCATION_MULTIPLIER ); allocatedOptions = IOptionsPurchaseQueue(optionsPurchaseQueue) .getOptionsAllocation(address(this), allocatedOptions); if (allocatedOptions != 0) { IERC20(option).approve(optionsPurchaseQueue, allocatedOptions); IOptionsPurchaseQueue(optionsPurchaseQueue).allocateOptions( allocatedOptions ); } } return allocatedOptions; } /** * @notice Sell the allocated options to the purchase queue post auction settlement * @dev Reverts if the auction hasn't settled yet * @param optionsPurchaseQueue is the OptionsPurchaseQueue contract * @param gnosisEasyAuction The address of the Gnosis Easy Auction contract * @return totalPremiums Total premiums earnt by the vault */ function sellOptionsToQueue( address optionsPurchaseQueue, address gnosisEasyAuction, uint256 optionAuctionID ) external returns (uint256) { uint256 settlementPrice = getAuctionSettlementPrice(gnosisEasyAuction, optionAuctionID); require(settlementPrice != 0, "!settlementPrice"); return IOptionsPurchaseQueue(optionsPurchaseQueue).sellToBuyers( settlementPrice ); } /** * @notice Gets the settlement price of a settled auction * @param gnosisEasyAuction The address of the Gnosis Easy Auction contract * @return settlementPrice Auction settlement price */ function getAuctionSettlementPrice( address gnosisEasyAuction, uint256 optionAuctionID ) public view returns (uint256) { bytes32 clearingPriceOrder = IGnosisAuction(gnosisEasyAuction) .auctionData(optionAuctionID) .clearingPriceOrder; if (clearingPriceOrder == bytes32(0)) { // Current auction hasn't settled yet return 0; } else { // We decode the clearingPriceOrder to find the auction settlement price // settlementPrice = clearingPriceOrder.sellAmount / clearingPriceOrder.buyAmount return (10**Vault.OTOKEN_DECIMALS) .mul( uint96(uint256(clearingPriceOrder)) // sellAmount ) .div( uint96(uint256(clearingPriceOrder) >> 96) // buyAmount ); } } /** * @notice Verify the constructor params satisfy requirements * @param owner is the owner of the vault with critical permissions * @param feeRecipient is the address to recieve vault performance and management fees * @param performanceFee is the perfomance fee pct. * @param tokenName is the name of the token * @param tokenSymbol is the symbol of the token * @param _vaultParams is the struct with vault general data */ function verifyInitializerParams( address owner, address keeper, address feeRecipient, uint256 performanceFee, uint256 managementFee, string calldata tokenName, string calldata tokenSymbol, Vault.VaultParams calldata _vaultParams ) external pure { require(owner != address(0), "!owner"); require(keeper != address(0), "!keeper"); require(feeRecipient != address(0), "!feeRecipient"); require( performanceFee < 100 * Vault.FEE_MULTIPLIER, "performanceFee >= 100%" ); require( managementFee < 100 * Vault.FEE_MULTIPLIER, "managementFee >= 100%" ); require(bytes(tokenName).length > 0, "!tokenName"); require(bytes(tokenSymbol).length > 0, "!tokenSymbol"); require(_vaultParams.asset != address(0), "!asset"); require(_vaultParams.underlying != address(0), "!underlying"); require(_vaultParams.minimumSupply > 0, "!minimumSupply"); require(_vaultParams.cap > 0, "!cap"); require( _vaultParams.cap > _vaultParams.minimumSupply, "cap has to be higher than minimumSupply" ); } /** * @notice Gets the next option expiry timestamp * @param currentOption is the otoken address that the vault is currently writing */ function getNextExpiry(address currentOption) internal view returns (uint256) { // uninitialized state if (currentOption == address(0)) { return getNextFriday(block.timestamp); } uint256 currentExpiry = IOtoken(currentOption).expiryTimestamp(); // After options expiry if no options are written for >1 week // We need to give the ability continue writing options if (block.timestamp > currentExpiry + 7 days) { return getNextFriday(block.timestamp); } return getNextFriday(currentExpiry); } /** * @notice Gets the next options expiry timestamp * @param timestamp is the expiry timestamp of the current option * Reference: https://codereview.stackexchange.com/a/33532 * Examples: * getNextFriday(week 1 thursday) -> week 1 friday * getNextFriday(week 1 friday) -> week 2 friday * getNextFriday(week 1 saturday) -> week 2 friday */ function getNextFriday(uint256 timestamp) internal pure returns (uint256) { // dayOfWeek = 0 (sunday) - 6 (saturday) uint256 dayOfWeek = ((timestamp / 1 days) + 4) % 7; uint256 nextFriday = timestamp + ((7 + 5 - dayOfWeek) % 7) * 1 days; uint256 friday8am = nextFriday - (nextFriday % (24 hours)) + (8 hours); // If the passed timestamp is day=Friday hour>8am, we simply increment it by a week to next Friday if (timestamp >= friday8am) { friday8am += 7 days; } return friday8am; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; library Vault { /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ // Fees are 6-decimal places. For example: 20 * 10**6 = 20% uint256 internal constant FEE_MULTIPLIER = 10**6; // Premium discount has 1-decimal place. For example: 80 * 10**1 = 80%. Which represents a 20% discount. uint256 internal constant PREMIUM_DISCOUNT_MULTIPLIER = 10; // Otokens have 8 decimal places. uint256 internal constant OTOKEN_DECIMALS = 8; // Percentage of funds allocated to options is 2 decimal places. 10 * 10**2 = 10% uint256 internal constant OPTION_ALLOCATION_MULTIPLIER = 10**2; // Placeholder uint value to prevent cold writes uint256 internal constant PLACEHOLDER_UINT = 1; struct VaultParams { // Option type the vault is selling bool isPut; // Token decimals for vault shares uint8 decimals; // Asset used in Theta / Delta Vault address asset; // Underlying asset of the options sold by vault address underlying; // Minimum supply of the vault shares issued, for ETH it's 10**10 uint56 minimumSupply; // Vault cap uint104 cap; } struct OptionState { // Option that the vault is shorting / longing in the next cycle address nextOption; // Option that the vault is currently shorting / longing address currentOption; // The timestamp when the `nextOption` can be used by the vault uint32 nextOptionReadyAt; } struct VaultState { // 32 byte slot 1 // Current round number. `round` represents the number of `period`s elapsed. uint16 round; // Amount that is currently locked for selling options uint104 lockedAmount; // Amount that was locked for selling options in the previous round // used for calculating performance fee deduction uint104 lastLockedAmount; // 32 byte slot 2 // Stores the total tally of how much of `asset` there is // to be used to mint rTHETA tokens uint128 totalPending; // Amount locked for scheduled withdrawals; uint128 queuedWithdrawShares; } struct DepositReceipt { // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years. uint16 round; // Deposit amount, max 20,282,409,603,651 or 20 trillion ETH deposit uint104 amount; // Unredeemed shares balance uint128 unredeemedShares; } struct Withdrawal { // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years. uint16 round; // Number of shares withdrawn uint128 shares; } struct AuctionSellOrder { // Amount of `asset` token offered in auction uint96 sellAmount; // Amount of oToken requested in auction uint96 buyAmount; // User Id of delta vault in latest gnosis auction uint64 userId; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {Vault} from "./Vault.sol"; library ShareMath { using SafeMath for uint256; uint256 internal constant PLACEHOLDER_UINT = 1; function assetToShares( uint256 assetAmount, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256) { // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet // which should never happen. // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes. require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare"); return assetAmount.mul(10**decimals).div(assetPerShare); } function sharesToAsset( uint256 shares, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256) { // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet // which should never happen. // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes. require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare"); return shares.mul(assetPerShare).div(10**decimals); } /** * @notice Returns the shares unredeemed by the user given their DepositReceipt * @param depositReceipt is the user's deposit receipt * @param currentRound is the `round` stored on the vault * @param assetPerShare is the price in asset per share * @param decimals is the number of decimals the asset/shares use * @return unredeemedShares is the user's virtual balance of shares that are owed */ function getSharesFromReceipt( Vault.DepositReceipt memory depositReceipt, uint256 currentRound, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256 unredeemedShares) { if (depositReceipt.round > 0 && depositReceipt.round < currentRound) { uint256 sharesFromRound = assetToShares(depositReceipt.amount, assetPerShare, decimals); return uint256(depositReceipt.unredeemedShares).add(sharesFromRound); } return depositReceipt.unredeemedShares; } function pricePerShare( uint256 totalSupply, uint256 totalBalance, uint256 pendingAmount, uint256 decimals ) internal pure returns (uint256) { uint256 singleShare = 10**decimals; return totalSupply > 0 ? singleShare.mul(totalBalance.sub(pendingAmount)).div( totalSupply ) : singleShare; } /************************************************ * HELPERS ***********************************************/ function assertUint104(uint256 num) internal pure { require(num <= type(uint104).max, "Overflow uint104"); } function assertUint128(uint256 num) internal pure { require(num <= type(uint128).max, "Overflow uint128"); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; interface IWSTETH { function getStETHByWstETH(uint256 _amount) external view returns (uint256); function getWstETHByStETH(uint256 _amount) external view returns (uint256); function stEthPerToken() external view returns (uint256); function tokensPerStEth() external view returns (uint256); function stETH() external view returns (address); function wrap(uint256 _amount) external returns (uint256); function unwrap(uint256 _amount) external returns (uint256); function approve(address _recipient, uint256 _amount) external returns (bool); 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 transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function decimals() external view returns (uint256); } interface ISTETH { function getBufferedEther(uint256 _amount) external view returns (uint256); function getPooledEthByShares(uint256 _amount) external view returns (uint256); function getSharesByPooledEth(uint256 _amount) external view returns (uint256); function submit(address _referralAddress) external payable returns (uint256); function withdraw(uint256 _amount, bytes32 _pubkeyHash) external returns (uint256); function approve(address _recipient, uint256 _amount) external returns (bool); 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 transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function decimals() external view returns (uint256); function getTotalShares() external view returns (uint256); function getTotalPooledEther() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; interface IWETH { function deposit() external payable; function withdraw(uint256) external; 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); function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; interface ICRV { function get_dy( int128 _indexIn, int128 _indexOut, uint256 _amountIn ) external view returns (uint256); // https://github.com/curvefi/curve-contract/blob/ // b0bbf77f8f93c9c5f4e415bce9cd71f0cdee960e/contracts/pools/steth/StableSwapSTETH.vy#L431 function exchange( int128 _indexIn, int128 _indexOut, uint256 _amountIn, uint256 _minAmountOut ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {Vault} from "../libraries/Vault.sol"; interface IRibbonVault { function deposit(uint256 amount) external; function depositETH() external payable; function cap() external view returns (uint256); function depositFor(uint256 amount, address creditor) external; function vaultParams() external view returns (Vault.VaultParams memory); } interface IStrikeSelection { function getStrikePrice(uint256 expiryTimestamp, bool isPut) external view returns (uint256, uint256); function delta() external view returns (uint256); } interface IOptionsPremiumPricer { function getPremium( uint256 strikePrice, uint256 timeToExpiry, bool isPut ) external view returns (uint256); function getPremiumInStables( uint256 strikePrice, uint256 timeToExpiry, bool isPut ) external view returns (uint256); function getOptionDelta( uint256 spotPrice, uint256 strikePrice, uint256 volatility, uint256 expiryTimestamp ) external view returns (uint256 delta); function getUnderlyingPrice() external view returns (uint256); function priceOracle() external view returns (address); function volatilityOracle() external view returns (address); function optionId() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; library GammaTypes { // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral // in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } } interface IOtoken { function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); } interface IOtokenFactory { function getOtoken( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external view returns (address); function createOtoken( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external returns (address); function getTargetOtokenAddress( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external view returns (address); event OtokenCreated( address tokenAddress, address creator, address indexed underlying, address indexed strike, address indexed collateral, uint256 strikePrice, uint256 expiry, bool isPut ); } interface IController { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets // but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } function getPayout(address _otoken, uint256 _amount) external view returns (uint256); function operate(ActionArgs[] calldata _actions) external; function getAccountVaultCounter(address owner) external view returns (uint256); function oracle() external view returns (address); function getVault(address _owner, uint256 _vaultId) external view returns (GammaTypes.Vault memory); function getProceed(address _owner, uint256 _vaultId) external view returns (uint256); function isSettlementAllowed( address _underlying, address _strike, address _collateral, uint256 _expiry ) external view returns (bool); } interface IOracle { function setAssetPricer(address _asset, address _pricer) external; function updateAssetPricer(address _asset, address _pricer) external; function getPrice(address _asset) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Detailed is IERC20 { function decimals() external view returns (uint8); function symbol() external view returns (string calldata); function name() external view returns (string calldata); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {DSMath} from "../vendor/DSMath.sol"; import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol"; import {IOtoken} from "../interfaces/GammaInterface.sol"; import {IOptionsPremiumPricer} from "../interfaces/IRibbon.sol"; import {Vault} from "./Vault.sol"; import {IRibbonThetaVault} from "../interfaces/IRibbonThetaVault.sol"; library GnosisAuction { using SafeMath for uint256; using SafeERC20 for IERC20; event InitiateGnosisAuction( address indexed auctioningToken, address indexed biddingToken, uint256 auctionCounter, address indexed manager ); event PlaceAuctionBid( uint256 auctionId, address indexed auctioningToken, uint256 sellAmount, uint256 buyAmount, address indexed bidder ); struct AuctionDetails { address oTokenAddress; address gnosisEasyAuction; address asset; uint256 assetDecimals; uint256 oTokenPremium; uint256 duration; } struct BidDetails { address oTokenAddress; address gnosisEasyAuction; address asset; uint256 assetDecimals; uint256 auctionId; uint256 lockedBalance; uint256 optionAllocation; uint256 optionPremium; address bidder; } function startAuction(AuctionDetails calldata auctionDetails) internal returns (uint256 auctionID) { uint256 oTokenSellAmount = getOTokenSellAmount(auctionDetails.oTokenAddress); require(oTokenSellAmount > 0, "No otokens to sell"); IERC20(auctionDetails.oTokenAddress).safeApprove( auctionDetails.gnosisEasyAuction, IERC20(auctionDetails.oTokenAddress).balanceOf(address(this)) ); // minBidAmount is total oTokens to sell * premium per oToken // shift decimals to correspond to decimals of USDC for puts // and underlying for calls uint256 minBidAmount = DSMath.wmul( oTokenSellAmount.mul(10**10), auctionDetails.oTokenPremium ); minBidAmount = auctionDetails.assetDecimals > 18 ? minBidAmount.mul(10**(auctionDetails.assetDecimals.sub(18))) : minBidAmount.div( 10**(uint256(18).sub(auctionDetails.assetDecimals)) ); require( minBidAmount <= type(uint96).max, "optionPremium * oTokenSellAmount > type(uint96) max value!" ); uint256 auctionEnd = block.timestamp.add(auctionDetails.duration); auctionID = IGnosisAuction(auctionDetails.gnosisEasyAuction) .initiateAuction( // address of oToken we minted and are selling auctionDetails.oTokenAddress, // address of asset we want in exchange for oTokens. Should match vault `asset` auctionDetails.asset, // orders can be cancelled at any time during the auction auctionEnd, // order will last for `duration` auctionEnd, // we are selling all of the otokens minus a fee taken by gnosis uint96(oTokenSellAmount), // the minimum we are willing to sell all the oTokens for. A discount is applied on black-scholes price uint96(minBidAmount), // the minimum bidding amount must be 1 * 10 ** -assetDecimals 1, // the min funding threshold 0, // no atomic closure false, // access manager contract address(0), // bytes for storing info like a whitelist for who can bid bytes("") ); emit InitiateGnosisAuction( auctionDetails.oTokenAddress, auctionDetails.asset, auctionID, msg.sender ); } function placeBid(BidDetails calldata bidDetails) internal returns ( uint256 sellAmount, uint256 buyAmount, uint64 userId ) { // calculate how much to allocate sellAmount = bidDetails .lockedBalance .mul(bidDetails.optionAllocation) .div(100 * Vault.OPTION_ALLOCATION_MULTIPLIER); // divide the `asset` sellAmount by the target premium per oToken to // get the number of oTokens to buy (8 decimals) buyAmount = sellAmount .mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS))) .div(bidDetails.optionPremium) .div(10**bidDetails.assetDecimals); require( sellAmount <= type(uint96).max, "sellAmount > type(uint96) max value!" ); require( buyAmount <= type(uint96).max, "buyAmount > type(uint96) max value!" ); // approve that amount IERC20(bidDetails.asset).safeApprove( bidDetails.gnosisEasyAuction, sellAmount ); uint96[] memory _minBuyAmounts = new uint96[](1); uint96[] memory _sellAmounts = new uint96[](1); bytes32[] memory _prevSellOrders = new bytes32[](1); _minBuyAmounts[0] = uint96(buyAmount); _sellAmounts[0] = uint96(sellAmount); _prevSellOrders[ 0 ] = 0x0000000000000000000000000000000000000000000000000000000000000001; // place sell order with that amount userId = IGnosisAuction(bidDetails.gnosisEasyAuction).placeSellOrders( bidDetails.auctionId, _minBuyAmounts, _sellAmounts, _prevSellOrders, "0x" ); emit PlaceAuctionBid( bidDetails.auctionId, bidDetails.oTokenAddress, sellAmount, buyAmount, bidDetails.bidder ); return (sellAmount, buyAmount, userId); } function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault ) internal { bytes32 order = encodeOrder( auctionSellOrder.userId, auctionSellOrder.buyAmount, auctionSellOrder.sellAmount ); bytes32[] memory orders = new bytes32[](1); orders[0] = order; IGnosisAuction(gnosisEasyAuction).claimFromParticipantOrder( IRibbonThetaVault(counterpartyThetaVault).optionAuctionID(), orders ); } function getOTokenSellAmount(address oTokenAddress) internal view returns (uint256) { // We take our current oToken balance. That will be our sell amount // but otokens will be transferred to gnosis. uint256 oTokenSellAmount = IERC20(oTokenAddress).balanceOf(address(this)); require( oTokenSellAmount <= type(uint96).max, "oTokenSellAmount > type(uint96) max value!" ); return oTokenSellAmount; } function getOTokenPremiumInStables( address oTokenAddress, address optionsPremiumPricer, uint256 premiumDiscount ) internal view returns (uint256) { IOtoken newOToken = IOtoken(oTokenAddress); IOptionsPremiumPricer premiumPricer = IOptionsPremiumPricer(optionsPremiumPricer); // Apply black-scholes formula (from rvol library) to option given its features // and get price for 100 contracts denominated USDC for both call and put options uint256 optionPremium = premiumPricer.getPremiumInStables( newOToken.strikePrice(), newOToken.expiryTimestamp(), newOToken.isPut() ); // Apply a discount to incentivize arbitraguers optionPremium = optionPremium.mul(premiumDiscount).div( 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER ); require( optionPremium <= type(uint96).max, "optionPremium > type(uint96) max value!" ); return optionPremium; } function encodeOrder( uint64 userId, uint96 buyAmount, uint96 sellAmount ) internal pure returns (bytes32) { return bytes32( (uint256(userId) << 192) + (uint256(buyAmount) << 96) + uint256(sellAmount) ); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AuctionType { struct AuctionData { IERC20 auctioningToken; IERC20 biddingToken; uint256 orderCancellationEndDate; uint256 auctionEndDate; bytes32 initialAuctionOrder; uint256 minimumBiddingAmountPerOrder; uint256 interimSumBidAmount; bytes32 interimOrder; bytes32 clearingPriceOrder; uint96 volumeClearingPriceOrder; bool minFundingThresholdNotReached; bool isAtomicClosureAllowed; uint256 feeNumerator; uint256 minFundingThreshold; } } interface IGnosisAuction { function initiateAuction( address _auctioningToken, address _biddingToken, uint256 orderCancellationEndDate, uint256 auctionEndDate, uint96 _auctionedSellAmount, uint96 _minBuyAmount, uint256 minimumBiddingAmountPerOrder, uint256 minFundingThreshold, bool isAtomicClosureAllowed, address accessManagerContract, bytes memory accessManagerContractData ) external returns (uint256); function auctionCounter() external view returns (uint256); function auctionData(uint256 auctionId) external view returns (AuctionType.AuctionData memory); function auctionAccessManager(uint256 auctionId) external view returns (address); function auctionAccessData(uint256 auctionId) external view returns (bytes memory); function FEE_DENOMINATOR() external view returns (uint256); function feeNumerator() external view returns (uint256); function settleAuction(uint256 auctionId) external returns (bytes32); function placeSellOrders( uint256 auctionId, uint96[] memory _minBuyAmounts, uint96[] memory _sellAmounts, bytes32[] memory _prevSellOrders, bytes calldata allowListCallData ) external returns (uint64); function claimFromParticipantOrder( uint256 auctionId, bytes32[] memory orders ) external returns (uint256, uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IOptionsPurchaseQueue { /** * @dev Contains purchase request info * @param optionsAmount Amount of options to purchase * @param premiums Total premiums the buyer is spending to purchase the options (optionsAmount * ceilingPrice) * We need to track the premiums here since the ceilingPrice could change between the time the purchase was * requested and when the options are sold * @param buyer The buyer requesting this purchase */ struct Purchase { uint128 optionsAmount; // Slot 0 uint128 premiums; address buyer; // Slot 1 } function purchases(address, uint256) external view returns ( uint128, uint128, address ); function totalOptionsAmount(address) external view returns (uint256); function vaultAllocatedOptions(address) external view returns (uint256); function whitelistedBuyer(address) external view returns (bool); function minPurchaseAmount(address) external view returns (uint256); function ceilingPrice(address) external view returns (uint256); function getPurchases(address vault) external view returns (Purchase[] memory); function getPremiums(address vault, uint256 optionsAmount) external view returns (uint256); function getOptionsAllocation(address vault, uint256 allocatedOptions) external view returns (uint256); function requestPurchase(address vault, uint256 optionsAmount) external returns (uint256); function allocateOptions(uint256 allocatedOptions) external returns (uint256); function sellToBuyers(uint256 settlementPrice) external returns (uint256); function cancelAllPurchases(address vault) external; function addWhitelist(address buyer) external; function removeWhitelist(address buyer) external; function setCeilingPrice(address vault, uint256 price) external; function setMinPurchaseAmount(address vault, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * This library supports ERC20s that have quirks in their behavior. * One such ERC20 is USDT, which requires allowance to be 0 before calling approve. * We plan to update this library with ERC20s that display such idiosyncratic behavior. */ library SupportsNonCompliantERC20 { address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; function safeApproveNonCompliant( IERC20 token, address spender, uint256 amount ) internal { if (address(token) == USDT) { SafeERC20.safeApprove(token, spender, 0); } SafeERC20.safeApprove(token, spender, amount); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {Vault} from "../libraries/Vault.sol"; interface IRibbonThetaVault { function currentOption() external view returns (address); function nextOption() external view returns (address); function vaultParams() external view returns (Vault.VaultParams memory); function vaultState() external view returns (Vault.VaultState memory); function optionState() external view returns (Vault.OptionState memory); function optionAuctionID() external view returns (uint256); function pricePerShare() external view returns (uint256); function roundPricePerShare(uint256) external view returns (uint256); }
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 ====/ 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.
function getPayout(address _otoken, uint256 _amount) external view returns (uint256); function operate(ActionArgs[] calldata _actions) external; function getAccountVaultCounter(address owner) external view returns (uint256); function oracle() external view returns (address); function getVault(address _owner, uint256 _vaultId) external view returns (GammaTypes.Vault memory); function getProceed(address _owner, uint256 _vaultId) external view returns (uint256); function isSettlementAllowed( address _underlying, address _strike, address _collateral, uint256 _expiry ) external view returns (bool); } } pragma solidity =0.8.4; } pragma solidity ^0.8.0; function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; }
11,936,758
pragma solidity ^0.4.19; /* * * Domain on day 1: https://etherbonds.io/ * * This contract implements bond contracts on the Ethereum blockchain * - You can buy a bond for ETH (NominalPrice) * - While buying you can set a desirable MaturityDate * - After you reach the MaturityDate you can redeem the bond for the MaturityPrice * - MaturityPrice is always greater than the NominalPrice * - greater the MaturityDate = higher profit * - You can't redeem a bond after MaxRedeemTime * * For example, you bought a bond for 1 ETH which will mature in 1 month for 63% profit. * After the month you can redeem the bond and receive your 1.63 ETH. * * If you don't want to wait for your bond maturity you can sell it to another investor. * For example you bought a 1 year bond, 6 months have passed and you urgently need money. * You can sell the bond on a secondary market to other investors before the maturity date. * You can also redeem your bond prematurely but only for a part of the nominal price. * * !!! THIS IS A HIGH RISK INVESTMENT ASSET !!! * !!! THIS IS GAMBLING !!! * !!! THIS IS A PONZI SCHEME !!! * All funds invested are going to prev investors for the exception of FounderFee and AgentFee * * Bonds are generating profit due to NEW and NEW investors BUYING them * If the contract has no ETH in it you will FAIL to redeem your bond * However as soon as new bonds will be issued the contract will receive ETH and * you will be able to redeem the bond. * * You can also refer a friend for 10% of the bonds he buys. Your friend will also receive a referral bonus for trading with your code! * */ /* * ------------------------------ * Main functions are: * Buy() - to buy a new issued bond * Redeem() - to redeem your bond for profit * * BuyOnSecondaryMarket() - to buy a bond from other investors * PlaceSellOrder() - to place your bond on the secondary market for selling * CancelSellOrder() - stop selling your bond * Withdraw() - to withdraw agant commission or funds after selling a bond on the secondary market * ------------------------------ */ /** /* Math operations with safety checks */ contract SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function assert(bool assertion) internal pure { if (!assertion) { revert(); } } } contract EtherBonds is SafeMath { /* A founder can write here useful information */ /* For example current domain name or report a problem */ string public README = "STATUS_OK"; /* You can refer a friend and you will be receiving a bonus for EACH his deal */ /* The friend will also have a bonus but only once */ /* You should have at least one bond in your history to be an agent */ /* Just ask your friend to specify your wallet address with his FIRST deal */ uint32 AgentBonusInPercent = 10; /* A user gets a bonus for adding an agent for his first deal */ uint32 UserRefBonusInPercent = 3; /* How long it takes for a bond to mature */ uint32 MinMaturityTimeInDays = 30; // don't set less than 15 days uint32 MaxMaturityTimeInDays = 240; /* Minimum price of a bond */ uint MinNominalBondPrice = 0.006 ether; /* How much % of your bond you can redeem prematurely */ uint32 PrematureRedeemPartInPercent = 25; /* How much this option costs */ uint32 PrematureRedeemCostInPercent = 20; /* Be careful! */ /* If you don't redeem your bond AFTER its maturity date */ /* the bond will become irredeemable! */ uint32 RedeemRangeInDays = 1; uint32 ExtraRedeemRangeInDays = 3; /* However you can prolong your redeem period for a price */ uint32 ExtraRedeemRangeCostInPercent = 10; /* Founder takes a fee for each bond sold */ /* There is no way for a founder to take all the contract's money, fonder takes only the fee */ address public Founder; uint32 public FounderFeeInPercent = 5; /* Events */ event Issued(uint32 bondId, address owner); event Sold(uint32 bondId, address seller, address buyer, uint price); event SellOrderPlaced(uint32 bondId, address seller); event SellOrderCanceled(uint32 bondId, address seller); event Redeemed(uint32 bondId, address owner); struct Bond { /* Unique ID of a bond */ uint32 id; address owner; uint32 issueTime; uint32 maturityTime; uint32 redeemTime; /* A bond can't be redeemed after this date */ uint32 maxRedeemTime; bool canBeRedeemedPrematurely; uint nominalPrice; uint maturityPrice; /* You can resell your bond to another user */ uint sellingPrice; } uint32 NextBondID = 1; mapping(uint32 => Bond) public Bonds; struct UserInfo { /* This address will receive commission for this user trading */ address agent; uint32 totalBonds; mapping(uint32 => uint32) bonds; } mapping(address => UserInfo) public Users; mapping(address => uint) public Balances; /* MAIN */ function EtherBonds() public { Founder = msg.sender; } function ContractInfo() public view returns( string readme, uint32 agentBonusInPercent, uint32 userRefBonusInPercent, uint32 minMaturityTimeInDays, uint32 maxMaturityTimeInDays, uint minNominalBondPrice, uint32 prematureRedeemPartInPercent, uint32 prematureRedeemCostInPercent, uint32 redeemRangeInDays, uint32 extraRedeemRangeInDays, uint32 extraRedeemRangeCostInPercent, uint32 nextBondID, uint balance ) { readme = README; agentBonusInPercent = AgentBonusInPercent; userRefBonusInPercent = UserRefBonusInPercent; minMaturityTimeInDays = MinMaturityTimeInDays; maxMaturityTimeInDays = MaxMaturityTimeInDays; minNominalBondPrice = MinNominalBondPrice; prematureRedeemPartInPercent = PrematureRedeemPartInPercent; prematureRedeemCostInPercent = PrematureRedeemCostInPercent; redeemRangeInDays = RedeemRangeInDays; extraRedeemRangeInDays = ExtraRedeemRangeInDays; extraRedeemRangeCostInPercent = ExtraRedeemRangeCostInPercent; nextBondID = NextBondID; balance = this.balance; } /* This function calcs how much profit will a bond bring */ function MaturityPrice( uint nominalPrice, uint32 maturityTimeInDays, bool hasExtraRedeemRange, bool canBeRedeemedPrematurely, bool hasRefBonus ) public view returns(uint) { uint nominalPriceModifierInPercent = 100; if (hasExtraRedeemRange) { nominalPriceModifierInPercent = sub( nominalPriceModifierInPercent, ExtraRedeemRangeCostInPercent ); } if (canBeRedeemedPrematurely) { nominalPriceModifierInPercent = sub( nominalPriceModifierInPercent, PrematureRedeemCostInPercent ); } if (hasRefBonus) { nominalPriceModifierInPercent = add( nominalPriceModifierInPercent, UserRefBonusInPercent ); } nominalPrice = div( mul(nominalPrice, nominalPriceModifierInPercent), 100 ); //y = 1.177683 - 0.02134921*x + 0.001112346*x^2 - 0.000010194*x^3 + 0.00000005298844*x^4 /* 15days +7% 30days +30% 60days +138% 120days +700% 240days +9400% */ uint x = maturityTimeInDays; /* The formula will break if x < 15 */ require(x >= 15); var a = mul(2134921000, x); var b = mul(mul(111234600, x), x); var c = mul(mul(mul(1019400, x), x), x); var d = mul(mul(mul(mul(5298, x), x), x), x); var k = sub(sub(add(add(117168300000, b), d), a), c); k = div(k, 10000000); return div(mul(nominalPrice, k), 10000); } /* This function checks if you can change your bond back to money */ function CanBeRedeemed(Bond bond) internal view returns(bool) { return bond.issueTime > 0 && // a bond should be issued bond.owner != 0 && // it should should have an owner bond.redeemTime == 0 && // it should not be already redeemed bond.sellingPrice == 0 && // it should not be reserved for selling ( !IsPremature(bond.maturityTime) || // it should be mature / be redeemable prematurely bond.canBeRedeemedPrematurely ) && block.timestamp <= bond.maxRedeemTime; // be careful, you can't redeem too old bonds } /* For some external checkings we gonna to wrap this in a function */ function IsPremature(uint maturityTime) public view returns(bool) { return maturityTime > block.timestamp; } /* This is how you buy bonds on the primary market */ function Buy( uint32 maturityTimeInDays, bool hasExtraRedeemRange, bool canBeRedeemedPrematurely, address agent // you can leave it 0 ) public payable { /* We don't issue bonds cheaper than MinNominalBondPrice*/ require(msg.value >= MinNominalBondPrice); /* We don't issue bonds out of allowed maturity range */ require( maturityTimeInDays >= MinMaturityTimeInDays && maturityTimeInDays <= MaxMaturityTimeInDays ); /* You can have a bonus on your first deal if specify an agent */ bool hasRefBonus = false; /* On your first deal ... */ if (Users[msg.sender].agent == 0 && Users[msg.sender].totalBonds == 0) { /* ... you may specify an agent and get a bonus for this ... */ if (agent != 0) { /* ... the agent should have some bonds behind him */ if (Users[agent].totalBonds > 0) { Users[msg.sender].agent = agent; hasRefBonus = true; } else { agent = 0; } } } /* On all your next deals you will have the same agent as on the first one */ else { agent = Users[msg.sender].agent; } /* Issuing a new bond */ Bond memory newBond; newBond.id = NextBondID; newBond.owner = msg.sender; newBond.issueTime = uint32(block.timestamp); newBond.canBeRedeemedPrematurely = canBeRedeemedPrematurely; /* You cant redeem your bond for profit untill this date */ newBond.maturityTime = newBond.issueTime + maturityTimeInDays*24*60*60; /* Your time to redeem is limited */ newBond.maxRedeemTime = newBond.maturityTime + (hasExtraRedeemRange?ExtraRedeemRangeInDays:RedeemRangeInDays)*24*60*60; newBond.nominalPrice = msg.value; newBond.maturityPrice = MaturityPrice( newBond.nominalPrice, maturityTimeInDays, hasExtraRedeemRange, canBeRedeemedPrematurely, hasRefBonus ); Bonds[newBond.id] = newBond; NextBondID += 1; /* Linking the bond to the owner so later he can easily find it */ var user = Users[newBond.owner]; user.bonds[user.totalBonds] = newBond.id; user.totalBonds += 1; /* Notify all users about the issuing event */ Issued(newBond.id, newBond.owner); /* Founder's fee */ uint moneyToFounder = div( mul(newBond.nominalPrice, FounderFeeInPercent), 100 ); /* Agent bonus */ uint moneyToAgent = div( mul(newBond.nominalPrice, AgentBonusInPercent), 100 ); if (agent != 0 && moneyToAgent > 0) { /* Agent can potentially block user's trading attempts, so we dont use just .transfer*/ Balances[agent] = add(Balances[agent], moneyToAgent); } /* Founder always gets his fee */ require(moneyToFounder > 0); Founder.transfer(moneyToFounder); } /* You can also buy bonds on secondary market from other users */ function BuyOnSecondaryMarket(uint32 bondId) public payable { var bond = Bonds[bondId]; /* A bond you are buying should be issued */ require(bond.issueTime > 0); /* Checking, if the bond is a valuable asset */ require(bond.redeemTime == 0 && block.timestamp < bond.maxRedeemTime); var price = bond.sellingPrice; /* You can only buy a bond if an owner is selling it */ require(price > 0); /* You should have enough money to pay the owner */ require(price <= msg.value); /* It's ok if you accidentally transfer more money, we will send them back */ var residue = msg.value - price; /* Transfering the bond */ var oldOwner = bond.owner; var newOwner = msg.sender; require(newOwner != 0 && newOwner != oldOwner); bond.sellingPrice = 0; bond.owner = newOwner; var user = Users[bond.owner]; user.bonds[user.totalBonds] = bond.id; user.totalBonds += 1; /* Doublechecking the price */ require(add(price, residue) == msg.value); /* Notify all users about the exchange event */ Sold(bond.id, oldOwner, newOwner, price); /* Old owner can potentially block user's trading attempts, so we dont use just .transfer*/ Balances[oldOwner] = add(Balances[oldOwner], price); if (residue > 0) { /* If there is residue we will send it back */ newOwner.transfer(residue); } } /* You can sell your bond on the secondary market */ function PlaceSellOrder(uint32 bondId, uint sellingPrice) public { /* To protect from an accidental selling by 0 price */ /* The selling price should be in Wei */ require(sellingPrice >= MinNominalBondPrice); var bond = Bonds[bondId]; /* A bond you are selling should be issued */ require(bond.issueTime > 0); /* You can't update selling price, please, call CancelSellOrder beforehand */ require(bond.sellingPrice == 0); /* You can't sell useless bonds */ require(bond.redeemTime == 0 && block.timestamp < bond.maxRedeemTime); /* You should own a bond you're selling */ require(bond.owner == msg.sender); bond.sellingPrice = sellingPrice; /* Notify all users about you wanting to sell the bond */ SellOrderPlaced(bond.id, bond.owner); } /* You can cancel your sell order */ function CancelSellOrder(uint32 bondId) public { var bond = Bonds[bondId]; /* Bond should be reserved for selling */ require(bond.sellingPrice > 0); /* You should own a bond which sell order you're cancelling */ require(bond.owner == msg.sender); bond.sellingPrice = 0; /* Notify all users about cancelling the selling order */ SellOrderCanceled(bond.id, bond.owner); } /* Sometimes we can't just use .transfer for a security reason */ function Withdraw() public { require(Balances[msg.sender] > 0); /* Don't forget about double entering in .transfer! */ var money = Balances[msg.sender]; Balances[msg.sender] = 0; msg.sender.transfer(money); } /* You can redeem bonds back to the contract for profit */ /* But you need to wait till maturityTime */ /* This is the key function where you get profit for a bond you own */ function Redeem(uint32 bondId) public { var bond = Bonds[bondId]; require(CanBeRedeemed(bond)); /* You should own a bond you redeem */ require(bond.owner == msg.sender); /* If a bond has redeemTime it has been redeemed */ bond.redeemTime = uint32(block.timestamp); /* If it's a premature redeem you will only get PrematureRedeemPartInPercent of nominalPrice back */ if (IsPremature(bond.maturityTime)) { bond.maturityPrice = div( mul(bond.nominalPrice, PrematureRedeemPartInPercent), 100 ); } /* Notify all users about the redeem event */ Redeemed(bond.id, bond.owner); /* Transfer funds to the owner */ /* This is how you earn money */ bond.owner.transfer(bond.maturityPrice); } /* Be carefull, this function can return a bound of a differet owner if the bond was sold. Always check the bond owner */ function UserBondByOffset(uint32 offset) public view returns( uint32 bondId, bool canBeRedeemed, bool isPremature ) { var bond = Bonds[Users[msg.sender].bonds[offset]]; bondId = bond.id; canBeRedeemed = CanBeRedeemed(bond); isPremature = IsPremature(bond.maturityTime); } function BondInfoById(uint32 bondId) public view returns( bool canBeRedeemed, bool isPremature ) { var bond = Bonds[bondId]; canBeRedeemed = CanBeRedeemed(bond); isPremature = IsPremature(bond.maturityTime); } /* ADMIN */ function AdmChange_README(string value) public { require(msg.sender == Founder); README = value; } }
This function calcs how much profit will a bond bring /
function MaturityPrice( uint nominalPrice, uint32 maturityTimeInDays, bool hasExtraRedeemRange, bool canBeRedeemedPrematurely, bool hasRefBonus ) public view returns(uint) { uint nominalPriceModifierInPercent = 100; if (hasExtraRedeemRange) { nominalPriceModifierInPercent = sub( nominalPriceModifierInPercent, ExtraRedeemRangeCostInPercent ); } if (canBeRedeemedPrematurely) { nominalPriceModifierInPercent = sub( nominalPriceModifierInPercent, PrematureRedeemCostInPercent ); } if (hasRefBonus) { nominalPriceModifierInPercent = add( nominalPriceModifierInPercent, UserRefBonusInPercent ); } nominalPrice = div( mul(nominalPrice, nominalPriceModifierInPercent), 100 ); 30days +30% 60days +138% 120days +700% 240days +9400% uint x = maturityTimeInDays; var a = mul(2134921000, x); var b = mul(mul(111234600, x), x); var c = mul(mul(mul(1019400, x), x), x); var d = mul(mul(mul(mul(5298, x), x), x), x); var k = sub(sub(add(add(117168300000, b), d), a), c); k = div(k, 10000000); return div(mul(nominalPrice, k), 10000); }
5,401,591
./partial_match/42/0xFb4cB3485Fb93f8A4DeeF2dFEc4a6621e753b39b/sources/Dollar.sol
set by impl contract/ 1e18 = 100%
function setFlatFee(uint256 flatFee_) public onlyMinter() { flatFee = flatFee_; }
3,393,755
./full_match/1/0x05C1FDA8ccD7f392c0fe6555a9eE1214bf9BFb4a/sources/contracts/mystery-box/MysteryBox.sol
Function allows admin add authorised address. The function also logs what addresses were authorised for transparancy./
function authorise(address addressToAuth) public onlyOwner { _isAuthorised[addressToAuth] = true; emit Authorise(addressToAuth, true); }
8,355,798
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.24; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.4.24; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/interfaces/IBridgeValidators.sol pragma solidity 0.4.24; interface IBridgeValidators { function isValidator(address _validator) external view returns (bool); function requiredSignatures() external view returns (uint256); function owner() external view returns (address); } // File: contracts/upgradeable_contracts/ValidatorStorage.sol pragma solidity 0.4.24; contract ValidatorStorage { bytes32 internal constant VALIDATOR_CONTRACT = 0x5a74bb7e202fb8e4bf311841c7d64ec19df195fee77d7e7ae749b27921b6ddfe; // keccak256(abi.encodePacked("validatorContract")) } // File: contracts/upgradeable_contracts/Validatable.sol pragma solidity 0.4.24; contract Validatable is EternalStorage, ValidatorStorage { function validatorContract() public view returns (IBridgeValidators) { return IBridgeValidators(addressStorage[VALIDATOR_CONTRACT]); } modifier onlyValidator() { require(validatorContract().isValidator(msg.sender)); /* solcov ignore next */ _; } function requiredSignatures() public view returns (uint256) { return validatorContract().requiredSignatures(); } } // File: contracts/libraries/Message.sol pragma solidity 0.4.24; library Message { function addressArrayContains(address[] array, address value) internal pure returns (bool) { for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; } // layout of message :: bytes: // offset 0: 32 bytes :: uint256 - message length // offset 32: 20 bytes :: address - recipient address // offset 52: 32 bytes :: uint256 - value // offset 84: 32 bytes :: bytes32 - transaction hash // offset 116: 20 bytes :: address - contract address to prevent double spending // mload always reads 32 bytes. // so we can and have to start reading recipient at offset 20 instead of 32. // if we were to read at 32 the address would contain part of value and be corrupted. // when reading from offset 20 mload will read 12 bytes (most of them zeros) followed // by the 20 recipient address bytes and correctly convert it into an address. // this saves some storage/gas over the alternative solution // which is padding address to 32 bytes and reading recipient at offset 32. // for more details see discussion in: // https://github.com/paritytech/parity-bridge/issues/61 function parseMessage(bytes message) internal pure returns (address recipient, uint256 amount, bytes32 txHash, address contractAddress) { require(isMessageValid(message)); assembly { recipient := mload(add(message, 20)) amount := mload(add(message, 52)) txHash := mload(add(message, 84)) contractAddress := mload(add(message, 104)) } } function isMessageValid(bytes _msg) internal pure returns (bool) { return _msg.length == requiredMessageLength(); } function requiredMessageLength() internal pure returns (uint256) { return 104; } function recoverAddressFromSignedMessage(bytes signature, bytes message, bool isAMBMessage) internal pure returns (address) { require(signature.length == 65); bytes32 r; bytes32 s; bytes1 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := mload(add(signature, 0x60)) } require(uint8(v) == 27 || uint8(v) == 28); require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0); return ecrecover(hashMessage(message, isAMBMessage), uint8(v), r, s); } function hashMessage(bytes message, bool isAMBMessage) internal pure returns (bytes32) { bytes memory prefix = "\x19Ethereum Signed Message:\n"; if (isAMBMessage) { return keccak256(abi.encodePacked(prefix, uintToString(message.length), message)); } else { string memory msgLength = "104"; return keccak256(abi.encodePacked(prefix, msgLength, message)); } } /** * @dev Validates provided signatures, only first requiredSignatures() number * of signatures are going to be validated, these signatures should be from different validators. * @param _message bytes message used to generate signatures * @param _signatures bytes blob with signatures to be validated. * First byte X is a number of signatures in a blob, * next X bytes are v components of signatures, * next 32 * X bytes are r components of signatures, * next 32 * X bytes are s components of signatures. * @param _validatorContract contract, which conforms to the IBridgeValidators interface, * where info about current validators and required signatures is stored. * @param isAMBMessage true if _message is an AMB message with arbitrary length. */ function hasEnoughValidSignatures( bytes _message, bytes _signatures, IBridgeValidators _validatorContract, bool isAMBMessage ) internal view { require(isAMBMessage || isMessageValid(_message)); uint256 requiredSignatures = _validatorContract.requiredSignatures(); uint256 amount; assembly { amount := and(mload(add(_signatures, 1)), 0xff) } require(amount >= requiredSignatures); bytes32 hash = hashMessage(_message, isAMBMessage); address[] memory encounteredAddresses = new address[](requiredSignatures); for (uint256 i = 0; i < requiredSignatures; i++) { uint8 v; bytes32 r; bytes32 s; uint256 posr = 33 + amount + 32 * i; uint256 poss = posr + 32 * amount; assembly { v := mload(add(_signatures, add(2, i))) r := mload(add(_signatures, posr)) s := mload(add(_signatures, poss)) } address recoveredAddress = ecrecover(hash, v, r, s); require(_validatorContract.isValidator(recoveredAddress)); require(!addressArrayContains(encounteredAddresses, recoveredAddress)); encounteredAddresses[i] = recoveredAddress; } } function uintToString(uint256 i) internal pure returns (string) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = bytes1(48 + (i % 10)); i /= 10; } return string(bstr); } } // File: contracts/upgradeable_contracts/MessageRelay.sol pragma solidity 0.4.24; contract MessageRelay is EternalStorage { function relayedMessages(bytes32 _txHash) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))]; } function setRelayedMessages(bytes32 _txHash, bool _status) internal { boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))] = _status; } } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.4.24; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.4.24; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner()); /* solcov ignore next */ _; } } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.4.24; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/upgradeable_contracts/InitializableBridge.sol pragma solidity 0.4.24; contract InitializableBridge is Initializable { bytes32 internal constant DEPLOYED_AT_BLOCK = 0xb120ceec05576ad0c710bc6e85f1768535e27554458f05dcbb5c65b8c7a749b0; // keccak256(abi.encodePacked("deployedAtBlock")) function deployedAtBlock() external view returns (uint256) { return uintStorage[DEPLOYED_AT_BLOCK]; } } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.4.24; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); /* solcov ignore next */ _; } /** * @dev Throws if called by any account other than contract itself or owner. */ modifier onlyRelevantSender() { // proxy owner if used through proxy, address(0) otherwise require( !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); /* solcov ignore next */ _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[OWNER]; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner the address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.4.24; contract Sacrifice { constructor(address _recipient) public payable { selfdestruct(_recipient); } } // File: contracts/libraries/Address.sol pragma solidity 0.4.24; /** * @title Address * @dev Helper methods for Address type. */ library Address { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address _receiver, uint256 _value) internal { if (!_receiver.send(_value)) { (new Sacrifice).value(_value)(_receiver); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/interfaces/ERC677.sol pragma solidity 0.4.24; contract ERC677 is ERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address, uint256, bytes) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) public returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); } contract LegacyERC20 { function transfer(address _spender, uint256 _value) public; // returns (bool); function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool); } // File: contracts/libraries/SafeERC20.sol pragma solidity 0.4.24; /** * @title SafeERC20 * @dev Helper methods for safe token transfers. * Functions perform additional checks to be sure that token transfer really happened. */ library SafeERC20 { using SafeMath for uint256; /** * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _to address of the receiver * @param _value amount of tokens to send */ function safeTransfer(address _token, address _to, uint256 _value) internal { LegacyERC20(_token).transfer(_to, _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } /** * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _from address of the sender * @param _value amount of tokens to send */ function safeTransferFrom(address _token, address _from, uint256 _value) internal { LegacyERC20(_token).transferFrom(_from, address(this), _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.4.24; /** * @title Claimable * @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations. */ contract Claimable { using SafeERC20 for address; /** * Throws if a given address is equal to address(0) */ modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimValues(address _token, address _to) internal validAddress(_to) { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; Address.safeSendValue(_to, value); } /** * @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function claimErc20Tokens(address _token, address _to) internal { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); _token.safeTransfer(_to, balance); } } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.4.24; contract VersionableBridge { function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (6, 1, 0); } /* solcov ignore next */ function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/DecimalShiftBridge.sol pragma solidity 0.4.24; contract DecimalShiftBridge is EternalStorage { using SafeMath for uint256; bytes32 internal constant DECIMAL_SHIFT = 0x1e8ecaafaddea96ed9ac6d2642dcdfe1bebe58a930b1085842d8fc122b371ee5; // keccak256(abi.encodePacked("decimalShift")) /** * @dev Internal function for setting the decimal shift for bridge operations. * Decimal shift can be positive, negative, or equal to zero. * It has the following meaning: N tokens in the foreign chain are equivalent to N * pow(10, shift) tokens on the home side. * @param _shift new value of decimal shift. */ function _setDecimalShift(int256 _shift) internal { // since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values require(_shift > -77 && _shift < 77); uintStorage[DECIMAL_SHIFT] = uint256(_shift); } /** * @dev Returns the value of foreign-to-home decimal shift. * @return decimal shift. */ function decimalShift() public view returns (int256) { return int256(uintStorage[DECIMAL_SHIFT]); } /** * @dev Converts the amount of home tokens into the equivalent amount of foreign tokens. * @param _value amount of home tokens. * @return equivalent amount of foreign tokens. */ function _unshiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, -decimalShift()); } /** * @dev Converts the amount of foreign tokens into the equivalent amount of home tokens. * @param _value amount of foreign tokens. * @return equivalent amount of home tokens. */ function _shiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, decimalShift()); } /** * @dev Calculates _value * pow(10, _shift). * @param _value amount of tokens. * @param _shift decimal shift to apply. * @return shifted value. */ function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) { if (_shift == 0) { return _value; } if (_shift > 0) { return _value.mul(10**uint256(_shift)); } return _value.div(10**uint256(-_shift)); } } // File: contracts/upgradeable_contracts/BasicBridge.sol pragma solidity 0.4.24; contract BasicBridge is InitializableBridge, Validatable, Ownable, Upgradeable, Claimable, VersionableBridge, DecimalShiftBridge { event GasPriceChanged(uint256 gasPrice); event RequiredBlockConfirmationChanged(uint256 requiredBlockConfirmations); bytes32 internal constant GAS_PRICE = 0x55b3774520b5993024893d303890baa4e84b1244a43c60034d1ced2d3cf2b04b; // keccak256(abi.encodePacked("gasPrice")) bytes32 internal constant REQUIRED_BLOCK_CONFIRMATIONS = 0x916daedf6915000ff68ced2f0b6773fe6f2582237f92c3c95bb4d79407230071; // keccak256(abi.encodePacked("requiredBlockConfirmations")) /** * @dev Public setter for fallback gas price value. Only bridge owner can call this method. * @param _gasPrice new value for the gas price. */ function setGasPrice(uint256 _gasPrice) external onlyOwner { _setGasPrice(_gasPrice); } function gasPrice() external view returns (uint256) { return uintStorage[GAS_PRICE]; } function setRequiredBlockConfirmations(uint256 _blockConfirmations) external onlyOwner { _setRequiredBlockConfirmations(_blockConfirmations); } function _setRequiredBlockConfirmations(uint256 _blockConfirmations) internal { require(_blockConfirmations > 0); uintStorage[REQUIRED_BLOCK_CONFIRMATIONS] = _blockConfirmations; emit RequiredBlockConfirmationChanged(_blockConfirmations); } function requiredBlockConfirmations() external view returns (uint256) { return uintStorage[REQUIRED_BLOCK_CONFIRMATIONS]; } /** * @dev Internal function for updating fallback gas price value. * @param _gasPrice new value for the gas price, zero gas price is allowed. */ function _setGasPrice(uint256 _gasPrice) internal { uintStorage[GAS_PRICE] = _gasPrice; emit GasPriceChanged(_gasPrice); } } // File: contracts/upgradeable_contracts/BasicTokenBridge.sol pragma solidity 0.4.24; contract BasicTokenBridge is EternalStorage, Ownable, DecimalShiftBridge { using SafeMath for uint256; event DailyLimitChanged(uint256 newLimit); event ExecutionDailyLimitChanged(uint256 newLimit); bytes32 internal constant MIN_PER_TX = 0xbbb088c505d18e049d114c7c91f11724e69c55ad6c5397e2b929e68b41fa05d1; // keccak256(abi.encodePacked("minPerTx")) bytes32 internal constant MAX_PER_TX = 0x0f8803acad17c63ee38bf2de71e1888bc7a079a6f73658e274b08018bea4e29c; // keccak256(abi.encodePacked("maxPerTx")) bytes32 internal constant DAILY_LIMIT = 0x4a6a899679f26b73530d8cf1001e83b6f7702e04b6fdb98f3c62dc7e47e041a5; // keccak256(abi.encodePacked("dailyLimit")) bytes32 internal constant EXECUTION_MAX_PER_TX = 0xc0ed44c192c86d1cc1ba51340b032c2766b4a2b0041031de13c46dd7104888d5; // keccak256(abi.encodePacked("executionMaxPerTx")) bytes32 internal constant EXECUTION_DAILY_LIMIT = 0x21dbcab260e413c20dc13c28b7db95e2b423d1135f42bb8b7d5214a92270d237; // keccak256(abi.encodePacked("executionDailyLimit")) function totalSpentPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))]; } function totalExecutedPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))]; } function dailyLimit() public view returns (uint256) { return uintStorage[DAILY_LIMIT]; } function executionDailyLimit() public view returns (uint256) { return uintStorage[EXECUTION_DAILY_LIMIT]; } function maxPerTx() public view returns (uint256) { return uintStorage[MAX_PER_TX]; } function executionMaxPerTx() public view returns (uint256) { return uintStorage[EXECUTION_MAX_PER_TX]; } function minPerTx() public view returns (uint256) { return uintStorage[MIN_PER_TX]; } function withinLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(getCurrentDay()).add(_amount); return dailyLimit() >= nextLimit && _amount <= maxPerTx() && _amount >= minPerTx(); } function withinExecutionLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(getCurrentDay()).add(_amount); return executionDailyLimit() >= nextLimit && _amount <= executionMaxPerTx(); } function getCurrentDay() public view returns (uint256) { return now / 1 days; } function addTotalSpentPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))] = totalSpentPerDay(_day).add(_value); } function addTotalExecutedPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))] = totalExecutedPerDay(_day).add(_value); } function setDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > maxPerTx() || _dailyLimit == 0); uintStorage[DAILY_LIMIT] = _dailyLimit; emit DailyLimitChanged(_dailyLimit); } function setExecutionDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > executionMaxPerTx() || _dailyLimit == 0); uintStorage[EXECUTION_DAILY_LIMIT] = _dailyLimit; emit ExecutionDailyLimitChanged(_dailyLimit); } function setExecutionMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx < executionDailyLimit()); uintStorage[EXECUTION_MAX_PER_TX] = _maxPerTx; } function setMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx == 0 || (_maxPerTx > minPerTx() && _maxPerTx < dailyLimit())); uintStorage[MAX_PER_TX] = _maxPerTx; } function setMinPerTx(uint256 _minPerTx) external onlyOwner { require(_minPerTx > 0 && _minPerTx < dailyLimit() && _minPerTx < maxPerTx()); uintStorage[MIN_PER_TX] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx() public view returns (uint256) { uint256 _maxPerTx = maxPerTx(); uint256 _dailyLimit = dailyLimit(); uint256 _spent = totalSpentPerDay(getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } function _setLimits(uint256[3] _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[DAILY_LIMIT] = _limits[0]; uintStorage[MAX_PER_TX] = _limits[1]; uintStorage[MIN_PER_TX] = _limits[2]; emit DailyLimitChanged(_limits[0]); } function _setExecutionLimits(uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[EXECUTION_DAILY_LIMIT] = _limits[0]; uintStorage[EXECUTION_MAX_PER_TX] = _limits[1]; emit ExecutionDailyLimitChanged(_limits[0]); } } // File: contracts/upgradeable_contracts/BasicForeignBridge.sol pragma solidity 0.4.24; contract BasicForeignBridge is EternalStorage, Validatable, BasicBridge, BasicTokenBridge, MessageRelay { /// triggered when relay of deposit from HomeBridge is complete event RelayedMessage(address recipient, uint256 value, bytes32 transactionHash); event UserRequestForAffirmation(address recipient, uint256 value); /** * @dev Validates provided signatures and relays a given message * @param message bytes to be relayed * @param signatures bytes blob with signatures to be validated */ function executeSignatures(bytes message, bytes signatures) external { Message.hasEnoughValidSignatures(message, signatures, validatorContract(), false); address recipient; uint256 amount; bytes32 txHash; address contractAddress; (recipient, amount, txHash, contractAddress) = Message.parseMessage(message); if (withinExecutionLimit(amount)) { require(contractAddress == address(this)); require(!relayedMessages(txHash)); setRelayedMessages(txHash, true); require(onExecuteMessage(recipient, amount, txHash)); emit RelayedMessage(recipient, amount, txHash); } else { onFailedMessage(recipient, amount, txHash); } } /** * @dev Internal function for updating fallback gas price value. * @param _gasPrice new value for the gas price, zero gas price is not allowed. */ function _setGasPrice(uint256 _gasPrice) internal { require(_gasPrice > 0); super._setGasPrice(_gasPrice); } /* solcov ignore next */ function onExecuteMessage(address, uint256, bytes32) internal returns (bool); /* solcov ignore next */ function onFailedMessage(address, uint256, bytes32) internal; } // File: contracts/upgradeable_contracts/ERC20Bridge.sol pragma solidity 0.4.24; contract ERC20Bridge is BasicForeignBridge { bytes32 internal constant ERC20_TOKEN = 0x15d63b18dbc21bf4438b7972d80076747e1d93c4f87552fe498c90cbde51665e; // keccak256(abi.encodePacked("erc20token")) function erc20token() public view returns (ERC20) { return ERC20(addressStorage[ERC20_TOKEN]); } function setErc20token(address _token) internal { require(AddressUtils.isContract(_token)); addressStorage[ERC20_TOKEN] = _token; } function relayTokens(address _receiver, uint256 _amount) external { require(_receiver != address(0)); require(_receiver != address(this)); require(_amount > 0); require(withinLimit(_amount)); addTotalSpentPerDay(getCurrentDay(), _amount); erc20token().transferFrom(msg.sender, address(this), _amount); emit UserRequestForAffirmation(_receiver, _amount); } } // File: contracts/upgradeable_contracts/OtherSideBridgeStorage.sol pragma solidity 0.4.24; contract OtherSideBridgeStorage is EternalStorage { bytes32 internal constant BRIDGE_CONTRACT = 0x71483949fe7a14d16644d63320f24d10cf1d60abecc30cc677a340e82b699dd2; // keccak256(abi.encodePacked("bridgeOnOtherSide")) function _setBridgeContractOnOtherSide(address _bridgeContract) internal { require(_bridgeContract != address(0)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } function bridgeContractOnOtherSide() internal view returns (address) { return addressStorage[BRIDGE_CONTRACT]; } } // File: contracts/upgradeable_contracts/erc20_to_native/ForeignBridgeErcToNative.sol pragma solidity 0.4.24; contract ForeignBridgeErcToNative is ERC20Bridge, OtherSideBridgeStorage { function initialize( address _validatorContract, address _erc20token, uint256 _requiredBlockConfirmations, uint256 _gasPrice, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _homeDailyLimitHomeMaxPerTxArray, //[ 0 = _homeDailyLimit, 1 = _homeMaxPerTx ] address _owner, int256 _decimalShift, address _bridgeOnOtherSide ) external onlyRelevantSender returns (bool) { require(!isInitialized()); require(AddressUtils.isContract(_validatorContract)); addressStorage[VALIDATOR_CONTRACT] = _validatorContract; setErc20token(_erc20token); uintStorage[DEPLOYED_AT_BLOCK] = block.number; _setRequiredBlockConfirmations(_requiredBlockConfirmations); _setGasPrice(_gasPrice); _setLimits(_dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(_homeDailyLimitHomeMaxPerTxArray); _setDecimalShift(_decimalShift); _setOwner(_owner); _setBridgeContractOnOtherSide(_bridgeOnOtherSide); setInitialize(); return isInitialized(); } function getBridgeMode() external pure returns (bytes4 _data) { return 0x18762d46; // bytes4(keccak256(abi.encodePacked("erc-to-native-core"))) } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Since bridged tokens are locked at this contract, it is not allowed to claim them with the use of claimTokens function require(_token != address(erc20token())); claimValues(_token, _to); } function onExecuteMessage( address _recipient, uint256 _amount, bytes32 /*_txHash*/ ) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), _amount); return erc20token().transfer(_recipient, _unshiftValue(_amount)); } function onFailedMessage(address, uint256, bytes32) internal { revert(); } function relayTokens(address _receiver, uint256 _amount) external { require(_receiver != bridgeContractOnOtherSide()); require(_receiver != address(0)); require(_receiver != address(this)); require(_amount > 0); require(withinLimit(_amount)); addTotalSpentPerDay(getCurrentDay(), _amount); erc20token().transferFrom(msg.sender, address(this), _amount); emit UserRequestForAffirmation(_receiver, _amount); } } // File: contracts/interfaces/IInterestReceiver.sol pragma solidity 0.4.24; interface IInterestReceiver { function onInterestReceived(address _token) external; } // File: contracts/upgradeable_contracts/erc20_to_native/InterestConnector.sol pragma solidity 0.4.24; /** * @title InterestConnector * @dev This contract gives an abstract way of receiving interest on locked tokens. */ contract InterestConnector is Ownable, ERC20Bridge { event PaidInterest(address indexed token, address to, uint256 value); /** * @dev Throws if interest is bearing not enabled. * @param token address, for which interest should be enabled. */ modifier interestEnabled(address token) { require(isInterestEnabled(token)); /* solcov ignore next */ _; } /** * @dev Ensures that caller is an EOA. * Functions with such modifier cannot be called from other contract (as well as from GSN-like approaches) */ modifier onlyEOA { // solhint-disable-next-line avoid-tx-origin require(msg.sender == tx.origin); /* solcov ignore next */ _; } /** * @dev Tells if interest earning was enabled for particular token. * @return true, if interest bearing is enabled. */ function isInterestEnabled(address _token) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("interestEnabled", _token))]; } /** * @dev Initializes interest receiving functionality. * Only owner can call this method. * @param _token address of the token for interest earning. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. * @param _minInterestPaid minimum amount of interest that can be paid in a single call. */ function initializeInterest( address _token, uint256 _minCashThreshold, uint256 _minInterestPaid, address _interestReceiver ) external onlyOwner { require(_isInterestSupported(_token)); require(!isInterestEnabled(_token)); _setInterestEnabled(_token, true); _setMinCashThreshold(_token, _minCashThreshold); _setMinInterestPaid(_token, _minInterestPaid); _setInterestReceiver(_token, _interestReceiver); } /** * @dev Sets minimum amount of tokens that cannot be invested. * Only owner can call this method. * @param _token address of the token contract. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. */ function setMinCashThreshold(address _token, uint256 _minCashThreshold) external onlyOwner { _setMinCashThreshold(_token, _minCashThreshold); } /** * @dev Tells minimum amount of tokens that are not being invested. * @param _token address of the invested token contract. * @return amount of tokens. */ function minCashThreshold(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))]; } /** * @dev Sets lower limit for the paid interest amount. * Only owner can call this method. * @param _token address of the token contract. * @param _minInterestPaid minimum amount of interest paid in a single call. */ function setMinInterestPaid(address _token, uint256 _minInterestPaid) external onlyOwner { _setMinInterestPaid(_token, _minInterestPaid); } /** * @dev Tells minimum amount of paid interest in a single call. * @param _token address of the invested token contract. * @return paid interest minimum limit. */ function minInterestPaid(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minInterestPaid", _token))]; } /** * @dev Internal function that disables interest for locked funds. * Only owner can call this method. * @param _token of token to disable interest for. */ function disableInterest(address _token) external onlyOwner { _withdraw(_token, uint256(-1)); _setInterestEnabled(_token, false); } /** * @dev Tells configured address of the interest receiver. * @param _token address of the invested token contract. * @return address of the interest receiver. */ function interestReceiver(address _token) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("interestReceiver", _token))]; } /** * Updates the interest receiver address. * Only owner can call this method. * @param _token address of the invested token contract. * @param _receiver new receiver address. */ function setInterestReceiver(address _token, address _receiver) external onlyOwner { _setInterestReceiver(_token, _receiver); } /** * @dev Pays collected interest for the specific underlying token. * Requires interest for the given token to be enabled. * @param _token address of the token contract. */ function payInterest(address _token) external onlyEOA interestEnabled(_token) { uint256 interest = interestAmount(_token); require(interest >= minInterestPaid(_token)); uint256 redeemed = _safeWithdrawTokens(_token, interest); _transferInterest(_token, redeemed); } /** * @dev Tells the amount of underlying tokens that are currently invested. * @param _token address of the token contract. * @return amount of underlying tokens. */ function investedAmount(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("investedAmount", _token))]; } /** * @dev Invests all excess tokens. * Requires interest for the given token to be enabled. * @param _token address of the token contract considered. */ function invest(address _token) public interestEnabled(_token) { uint256 balance = _selfBalance(_token); uint256 minCash = minCashThreshold(_token); require(balance > minCash); uint256 amount = balance - minCash; _setInvestedAmount(_token, investedAmount(_token).add(amount)); _invest(_token, amount); } /** * @dev Internal function for transferring interest. * Calls a callback on the receiver, if it is a contract. * @param _token address of the underlying token contract. * @param _amount amount of collected tokens that should be sent. */ function _transferInterest(address _token, uint256 _amount) internal { address receiver = interestReceiver(_token); require(receiver != address(0)); ERC20(_token).transfer(receiver, _amount); if (AddressUtils.isContract(receiver)) { IInterestReceiver(receiver).onInterestReceived(_token); } emit PaidInterest(_token, receiver, _amount); } /** * @dev Internal function for setting interest enabled flag for some token. * @param _token address of the token contract. * @param _enabled true to enable interest earning, false to disable. */ function _setInterestEnabled(address _token, bool _enabled) internal { boolStorage[keccak256(abi.encodePacked("interestEnabled", _token))] = _enabled; } /** * @dev Internal function for setting the amount of underlying tokens that are currently invested. * @param _token address of the token contract. * @param _amount new amount of invested tokens. */ function _setInvestedAmount(address _token, uint256 _amount) internal { uintStorage[keccak256(abi.encodePacked("investedAmount", _token))] = _amount; } /** * @dev Internal function for withdrawing some amount of the invested tokens. * Reverts if given amount cannot be withdrawn. * @param _token address of the token contract withdrawn. * @param _amount amount of requested tokens to be withdrawn. */ function _withdraw(address _token, uint256 _amount) internal { if (_amount == 0) return; uint256 invested = investedAmount(_token); uint256 withdrawal = _amount > invested ? invested : _amount; uint256 redeemed = _safeWithdrawTokens(_token, withdrawal); _setInvestedAmount(_token, invested > redeemed ? invested - redeemed : 0); } /** * @dev Internal function for safe withdrawal of invested tokens. * Reverts if given amount cannot be withdrawn. * Additionally verifies that at least _amount of tokens were withdrawn. * @param _token address of the token contract withdrawn. * @param _amount amount of requested tokens to be withdrawn. */ function _safeWithdrawTokens(address _token, uint256 _amount) private returns (uint256) { uint256 balance = _selfBalance(_token); _withdrawTokens(_token, _amount); uint256 redeemed = _selfBalance(_token) - balance; require(redeemed >= _amount); return redeemed; } /** * @dev Internal function for setting minimum amount of tokens that cannot be invested. * @param _token address of the token contract. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. */ function _setMinCashThreshold(address _token, uint256 _minCashThreshold) internal { uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))] = _minCashThreshold; } /** * @dev Internal function for setting lower limit for paid interest amount. * @param _token address of the token contract. * @param _minInterestPaid minimum amount of interest paid in a single call. */ function _setMinInterestPaid(address _token, uint256 _minInterestPaid) internal { uintStorage[keccak256(abi.encodePacked("minInterestPaid", _token))] = _minInterestPaid; } /** * @dev Internal function for setting interest receiver address. * @param _token address of the invested token contract. * @param _receiver address of the interest receiver. */ function _setInterestReceiver(address _token, address _receiver) internal { require(_receiver != address(this)); addressStorage[keccak256(abi.encodePacked("interestReceiver", _token))] = _receiver; } /** * @dev Tells this contract balance of some specific token contract * @param _token address of the token contract. * @return contract balance. */ function _selfBalance(address _token) internal view returns (uint256) { return ERC20(_token).balanceOf(address(this)); } function _isInterestSupported(address _token) internal pure returns (bool); function _invest(address _token, uint256 _amount) internal; function _withdrawTokens(address _token, uint256 _amount) internal; function interestAmount(address _token) public view returns (uint256); } // File: contracts/interfaces/ICToken.sol pragma solidity 0.4.24; interface ICToken { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function balanceOf(address account) external view returns (uint256); function balanceOfUnderlying(address account) external view returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 borrowAmount) external returns (uint256); } // File: contracts/interfaces/IComptroller.sol pragma solidity 0.4.24; interface IComptroller { function claimComp(address[] holders, address[] cTokens, bool borrowers, bool suppliers) external; } // File: contracts/upgradeable_contracts/erc20_to_native/CompoundConnector.sol pragma solidity 0.4.24; /** * @title CompoundConnector * @dev This contract allows to partially invest locked Dai tokens into Compound protocol. */ contract CompoundConnector is InterestConnector { uint256 internal constant SUCCESS = 0; /** * @dev Tells the address of the DAI token in the Ethereum Mainnet. */ function daiToken() public pure returns (ERC20) { return ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); } /** * @dev Tells the address of the cDAI token in the Ethereum Mainnet. */ function cDaiToken() public pure returns (ICToken) { return ICToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); } /** * @dev Tells the address of the Comptroller contract in the Ethereum Mainnet. */ function comptroller() public pure returns (IComptroller) { return IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); } /** * @dev Tells the address of the COMP token in the Ethereum Mainnet. */ function compToken() public pure returns (ERC20) { return ERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); } /** * @dev Tells the current earned interest amount. * @param _token address of the underlying token contract. * @return total amount of interest that can be withdrawn now. */ function interestAmount(address _token) public view returns (uint256) { uint256 underlyingBalance = cDaiToken().balanceOfUnderlying(address(this)); // 1 DAI is reserved for possible truncation/round errors uint256 invested = investedAmount(_token) + 1 ether; return underlyingBalance > invested ? underlyingBalance - invested : 0; } /** * @dev Tells if interest earning is supported for the specific token contract. * @param _token address of the token contract. * @return true, if interest earning is supported. */ function _isInterestSupported(address _token) internal pure returns (bool) { return _token == address(daiToken()); } /** * @dev Invests the given amount of tokens to the Compound protocol. * Converts _amount of TOKENs into X cTOKENs. * @param _token address of the token contract. * @param _amount amount of tokens to invest. */ function _invest(address _token, uint256 _amount) internal { (_token); daiToken().approve(address(cDaiToken()), _amount); require(cDaiToken().mint(_amount) == SUCCESS); } /** * @dev Withdraws at least the given amount of tokens from the Compound protocol. * Converts X cTOKENs into _amount of TOKENs. * @param _token address of the token contract. * @param _amount minimal amount of tokens to withdraw. */ function _withdrawTokens(address _token, uint256 _amount) internal { (_token); require(cDaiToken().redeemUnderlying(_amount) == SUCCESS); } /** * @dev Claims Comp token and transfers it to the associated interest receiver. */ function claimCompAndPay() external onlyEOA { address[] memory holders = new address[](1); holders[0] = address(this); address[] memory markets = new address[](1); markets[0] = address(cDaiToken()); comptroller().claimComp(holders, markets, false, true); address comp = address(compToken()); uint256 interest = _selfBalance(comp); require(interest >= minInterestPaid(comp)); _transferInterest(comp, interest); } } // File: contracts/gsn/interfaces/IRelayRecipient.sol // SPDX-License-Identifier:MIT pragma solidity 0.4.24; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public view returns (bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal view returns (bytes memory); function versionRecipient() external view returns (string memory); } // File: contracts/gsn/BaseRelayRecipient.sol // SPDX-License-Identifier:MIT // solhint-disable no-inline-assembly pragma solidity 0.4.24; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ contract BaseRelayRecipient is IRelayRecipient { /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96, calldataload(sub(calldatasize, 20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize, 20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr, 32), size) calldatacopy(add(ptr, 64), 0, size) return(ptr, add(size, 64)) } } else { return msg.data; } } } // File: contracts/gsn/interfaces/IKnowForwarderAddress.sol // SPDX-License-Identifier:MIT pragma solidity 0.4.24; interface IKnowForwarderAddress { /** * return the forwarder we trust to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function getTrustedForwarder() external view returns (address); } // File: contracts/upgradeable_contracts/GSNForeignERC20Bridge.sol pragma solidity 0.4.24; contract GSNForeignERC20Bridge is BasicForeignBridge, ERC20Bridge, BaseRelayRecipient, IKnowForwarderAddress { bytes32 internal constant PAYMASTER = 0xfefcc139ed357999ed60c6a013947328d52e7d9751e93fd0274a2bfae5cbcb12; // keccak256(abi.encodePacked("paymaster")) bytes32 internal constant TRUSTED_FORWARDER = 0x222cb212229f0f9bcd249029717af6845ea3d3a84f22b54e5744ac25ef224c92; // keccak256(abi.encodePacked("trustedForwarder")) function versionRecipient() external view returns (string memory) { return "1.0.1"; } function getTrustedForwarder() external view returns (address) { return addressStorage[TRUSTED_FORWARDER]; } function setTrustedForwarder(address _trustedForwarder) public onlyOwner { addressStorage[TRUSTED_FORWARDER] = _trustedForwarder; } function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == addressStorage[TRUSTED_FORWARDER]; } function setPayMaster(address _paymaster) public onlyOwner { addressStorage[PAYMASTER] = _paymaster; } /** * @param message same as in `executeSignatures` * @param signatures same as in `executeSignatures` * @param maxTokensFee maximum amount of foreign tokens that user allows to take * as a commission */ function executeSignaturesGSN(bytes message, bytes signatures, uint256 maxTokensFee) external { // Allow only forwarder calls require(isTrustedForwarder(msg.sender), "invalid forwarder"); Message.hasEnoughValidSignatures(message, signatures, validatorContract(), false); address recipient; uint256 amount; bytes32 txHash; address contractAddress; (recipient, amount, txHash, contractAddress) = Message.parseMessage(message); if (withinExecutionLimit(amount)) { require(maxTokensFee <= amount); require(contractAddress == address(this)); require(!relayedMessages(txHash)); setRelayedMessages(txHash, true); require(onExecuteMessageGSN(recipient, amount, maxTokensFee)); emit RelayedMessage(recipient, amount, txHash); } else { onFailedMessage(recipient, amount, txHash); } } function onExecuteMessageGSN(address recipient, uint256 amount, uint256 fee) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), amount); // Send maxTokensFee to paymaster ERC20 token = erc20token(); bool first = token.transfer(addressStorage[PAYMASTER], fee); bool second = token.transfer(recipient, amount - fee); return first && second; } } // File: contracts/upgradeable_contracts/erc20_to_native/XDaiForeignBridge.sol pragma solidity 0.4.24; contract XDaiForeignBridge is ForeignBridgeErcToNative, CompoundConnector, GSNForeignERC20Bridge { function initialize( address _validatorContract, address _erc20token, uint256 _requiredBlockConfirmations, uint256 _gasPrice, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _homeDailyLimitHomeMaxPerTxArray, //[ 0 = _homeDailyLimit, 1 = _homeMaxPerTx ] address _owner, int256 _decimalShift, address _bridgeOnOtherSide ) external onlyRelevantSender returns (bool) { require(!isInitialized()); require(AddressUtils.isContract(_validatorContract)); require(_erc20token == address(daiToken())); require(_decimalShift == 0); addressStorage[VALIDATOR_CONTRACT] = _validatorContract; uintStorage[DEPLOYED_AT_BLOCK] = block.number; _setRequiredBlockConfirmations(_requiredBlockConfirmations); _setGasPrice(_gasPrice); _setLimits(_dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(_homeDailyLimitHomeMaxPerTxArray); _setOwner(_owner); _setBridgeContractOnOtherSide(_bridgeOnOtherSide); setInitialize(); return isInitialized(); } function erc20token() public view returns (ERC20) { return daiToken(); } // selector 6a641d80 function migrateTo_6_1_0(address _interestReceiver) external { bytes32 upgradeStorage = 0x6a641d806674d4ce5e98c8fdab48e66c563660255f099d81d45fa2fe8ed9cc1d; // keccak256(abi.encodePacked('migrateTo_6_1_0(address)')) require(!boolStorage[upgradeStorage]); address dai = address(daiToken()); address comp = address(compToken()); _setInterestEnabled(dai, true); _setMinCashThreshold(dai, 1000000 ether); _setMinInterestPaid(dai, 1000 ether); _setInterestReceiver(dai, _interestReceiver); _setMinInterestPaid(comp, 1 ether); _setInterestReceiver(comp, _interestReceiver); invest(dai); boolStorage[upgradeStorage] = true; } function investDai() external { invest(address(daiToken())); } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Since bridged tokens are locked at this contract, it is not allowed to claim them with the use of claimTokens function address bridgedToken = address(daiToken()); require(_token != address(bridgedToken)); require(_token != address(cDaiToken()) || !isInterestEnabled(bridgedToken)); require(_token != address(compToken()) || !isInterestEnabled(bridgedToken)); claimValues(_token, _to); } function onExecuteMessage( address _recipient, uint256 _amount, bytes32 /*_txHash*/ ) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), _amount); ERC20 token = daiToken(); ensureEnoughTokens(token, _amount); return token.transfer(_recipient, _amount); } function onExecuteMessageGSN(address recipient, uint256 amount, uint256 fee) internal returns (bool) { ensureEnoughTokens(daiToken(), amount); return super.onExecuteMessageGSN(recipient, amount, fee); } function ensureEnoughTokens(ERC20 token, uint256 amount) internal { uint256 currentBalance = token.balanceOf(address(this)); if (currentBalance < amount) { uint256 withdrawAmount = (amount - currentBalance).add(minCashThreshold(address(token))); _withdraw(address(token), withdrawAmount); } } }
Tells configured address of the interest receiver. _token address of the invested token contract. return address of the interest receiver./
function interestReceiver(address _token) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("interestReceiver", _token))]; }
1,093,409
./partial_match/42/0x7cb7F6b5F1C850566F1152b2882263d6003386FF/sources/MasterchefDelegator.sol
get how much token will be mined from _toBlock to _toBlock.
function getRewardToken(uint256 _fromBlock, uint256 _toBlock) public view returns (uint256) { return calculateRewardToken( MINT_DECREASE_TERM, INITIAL_BONUS_PER_BLOCK, startBlock, _fromBlock, _toBlock ); }
3,335,105
./full_match/100/0xd4cf9665a3EF56F84B59953b1BCa28e6aEFE2566/sources/home/christoph/Documents/sandbox/GIF/dip-platform/gif-contracts/contracts/modules/query/QueryController.sol
Oracle Response / todo: send reward
function respond( uint256 _requestId, address _responder, bytes calldata _data ) external onlyOracleService isResponsibleOracle(_requestId, _responder) returns (uint256 _responseId) { OracleRequest storage req = oracleRequests[_requestId]; (bool status, ) = req.callbackContractAddress.call( abi.encodeWithSignature( string( abi.encodePacked(req.callbackMethodName, "(uint256,bytes)") ), _requestId, _data ) ); _responseId = oracleResponses.length; oracleResponses.push(OracleResponse( _requestId, _responder, block.timestamp, status )); emit LogOracleResponded(_requestId, _responseId, _responder, status); }
14,273,369
./partial_match/1/0x6B0B234fB2f380309D47A7E9391E29E9a179395a/sources/src/v0.8/dev/automation/2_1/interfaces/IAutomationRegistryConsumer.sol
IAutomationRegistryConsumer defines the LTS user-facing interface that we intend to maintain for across upgrades. As long as users use functions from within this interface, their upkeeps will retain backwards compatability across migrations. Functions can be added to this interface, but not removed./
interface IAutomationRegistryConsumer { function getBalance(uint256 id) external view returns (uint96 balance); function getMinBalance(uint256 id) external view returns (uint96 minBalance); function cancelUpkeep(uint256 id) external; function pauseUpkeep(uint256 id) external; function unpauseUpkeep(uint256 id) external; function addFunds(uint256 id, uint96 amount) external; function withdrawFunds(uint256 id, address to) external; pragma solidity ^0.8.4; }
3,963,184
pragma solidity ^0.4.18; library StringUtils { /** * @dev Checks if the passed string is not empty. */ function isNotEmpty( string memory _str) pure internal returns (bool) { bytes memory strBytes = bytes(_str); return strBytes.length > 0; } /** * @dev Checks if the passed string is empty. */ function isEmpty( string memory _str) pure internal returns (bool) { bytes memory strBytes = bytes(_str); return strBytes.length == 0; } /** * @dev Gets the hash of the string. */ function getHash( string storage _str) pure internal returns (bytes32) { return keccak256(_str); } /** * @dev Gets the hash of an empty string. */ function getEmptyStringHash() pure internal returns (bytes32) { return keccak256(""); } }
Gets the hash of an empty string./
function getEmptyStringHash() pure internal returns (bytes32) { return keccak256(""); }
12,639,697
./partial_match/1/0xB985eA1be961f7c4A4C45504444C02c88c4fdEF9/sources/lib/hats-module/lib/solady/src/utils/Clone.sol
Reads an immutable arg with type bytes. @solidity memory-safe-assembly
function _getArgBytes(uint256 argOffset, uint256 length) internal pure returns (bytes memory arg) { uint256 offset = _getImmutableArgsOffset(); assembly { arg := mload(0x40) calldatacopy(add(arg, 0x20), add(offset, argOffset), length) let o := add(add(arg, 0x20), length) } }
2,750,361
./partial_match/1/0xB690fC16279C096999264e3C049fA133024b4d69/sources/contracts/storefront/RandomExpansionStorefront.sol
Request a number of purchases on a sale, receving randomly distributed expansion NFTs saleId ID of sale purchaseQuantity How many times the sale is being purchased in a process presaleWhitelistedQuantity Whitelisted quantity to pair with address on leaf of merkle tree proof Merkle proof for purchaser (if presale and whitelisted) nftRecipient Recipient of minted NFTs/ require that this purchase request is fulfillable
function requestPurchaseExpansionPacks( uint256 saleId, uint32 purchaseQuantity, uint32 presaleWhitelistedQuantity, bytes32[] calldata proof, address nftRecipient ) external payable { Sale memory sale = _sales[saleId]; require(sale.packId != 0, "zero packId"); _validatePurchaseTimeAndProcessQuantity(sale, saleId, purchaseQuantity, presaleWhitelistedQuantity, proof); uint64 numMintRequests = _packIdToOutstandingMintRequestsV2[sale.tokenContract][sale.packId]; IExpansion.Pack memory packForSale = IExpansion(sale.tokenContract).getPack(sale.packId); require( numMintRequests + purchaseQuantity + packForSale.mintedCount <= packForSale.capacity || packForSale.capacity == 0, "cant service req" ); uint256 gasDeposit = _validateAndProcessPurchasePaymentRandom(sale, purchaseQuantity); numRandomExpansionPurchases += 1; _packIdToOutstandingMintRequestsV2[sale.tokenContract][sale.packId] = numMintRequests + purchaseQuantity; emit RandomExpansionPackPurchaseRequest( numRandomExpansionPurchases, saleId, purchaseQuantity, msg.sender, nftRecipient, false, _getPrefixHash(), gasDeposit ); }
3,599,522
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity >=0.5.10; import "ROOT/0x/utils/contracts/src/LibRichErrors.sol"; import "ROOT/0x/utils/contracts/src/LibBytes.sol"; import "ROOT/0x/erc20/contracts/src/interfaces/IERC20Token.sol"; library LibERC20Token { /// @dev Calls `IERC20Token(token).approve()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param allowance The allowance to set. function approve( address token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).approve.selector, spender, allowance ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).transfer()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transfer( address token, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transfer.selector, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).transferFrom()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param from The owner of the tokens. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transferFrom( address token, address from, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transferFrom.selector, from, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Executes a call on address `target` with calldata `callData` /// and asserts that either nothing was returned or a single boolean /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. function _callWithOptionalBooleanResult( address target, bytes memory callData ) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed) { if (resultData.length == 0) { return; } if (resultData.length == 32) { uint256 result = LibBytes.readUint256(resultData, 0); if (result == 1) { return; } } } revert(); //LibRichErrors.rrevert(resultData); } }
Executes a call on address `target` with calldata `callData` and asserts that either nothing was returned or a single boolean was returned equal to `true`. target The call target. callData The abi-encoded call data.
function _callWithOptionalBooleanResult( address target, bytes memory callData ) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed) { if (resultData.length == 0) { return; } if (resultData.length == 32) { uint256 result = LibBytes.readUint256(resultData, 0); if (result == 1) { return; } } } revert();
12,943,997
./partial_match/1/0xe3F565194bEAc96d4b991bB68C0654467B1E20F0/sources/contracts/UnipilotActiveVault.sol
Burns all the Unipilot position and HODL in the vault to prevent users from huge IL Only called by the governer or selected operators Users can also deposit/withdraw during HODL period.
function pullLiquidity(address recipient) external onlyOperator { require(unipilotFactory.isWhitelist(recipient)); ( uint256 reserves0, uint256 reserves1, uint256 fees0, uint256 fees1 ) = pool.burnLiquidity( ticksData.baseTickLower, ticksData.baseTickUpper, recipient ); if (recipient != address(this)) { pay(address(token0), address(this), recipient, _balance0()); pay(address(token1), address(this), recipient, _balance1()); } _pulled = 2; emit PullLiquidity(reserves0, reserves1, fees0, fees1); }
4,338,381
./partial_match/1/0xFAd7b174eB6b8838416B5b6Ac5675676Fb6106D4/sources/BITStationERC20.sol
Set allowance for other address Allows `_spender` to spend no more than `_value` tokens in your behalf _spender The address authorized to spend _value the max amount they can spend/
function approve(address _spender, uint256 _value) public returns (bool success) { require(!isLocked); allowance[msg.sender][_spender] = _value; return true; }
15,580,286
./full_match/1/0x34Edab6C42b9fAa988C05594Ded063c57EFC36F0/sources/contracts/NFT.sol
unstake a token _tokenIds array of token ids to unstake Prevents the token staking if it is already staked
function unstake(uint256[] calldata _tokenIds) external payable { for (uint256 i; i < _tokenIds.length; i++) { require(ownerOf(_tokenIds[i]) == msg.sender, "Not Token Owner"); require(tokenStakeStatus[_tokenIds[i]] > 0, "Not Staked"); delete tokenStakeStatus[_tokenIds[i]]; } emit Unstake(_tokenIds); }
3,844,582
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.12; pragma experimental ABIEncoderV2; // Part: Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // Part: Context /** * @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; } } // Part: IBZx /// @title A proxy interface for The Protocol /// @author bZeroX /// @notice This is just an interface, not to be deployed itself. /// @dev This interface is to be used for the protocol interactions. interface IBZx { ////// Protocol ////// /// @dev adds or replaces existing proxy module /// @param target target proxy module address function replaceContract(address target) external; /// @dev updates all proxy modules addreses and function signatures. /// sigsArr and targetsArr should be of equal length /// @param sigsArr array of function signatures /// @param targetsArr array of target proxy module addresses function setTargets( string[] calldata sigsArr, address[] calldata targetsArr ) external; /// @dev returns protocol module address given a function signature /// @return module address function getTarget(string calldata sig) external view returns (address); ////// Protocol Settings ////// /// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface /// @param newContract module address for the IPriceFeeds implementation function setPriceFeedContract(address newContract) external; /// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface /// @param newContract module address for the ISwapsImpl implementation function setSwapsImplContract(address newContract) external; /// @dev sets loan pool with assets. Accepts two arrays of equal length /// @param pools array of address of pools /// @param assets array of addresses of assets function setLoanPool(address[] calldata pools, address[] calldata assets) external; /// @dev updates list of supported tokens, it can be use also to disable or enable particualr token /// @param addrs array of address of pools /// @param toggles array of addresses of assets /// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.) function setSupportedTokens( address[] calldata addrs, bool[] calldata toggles, bool withApprovals ) external; /// @dev sets approvals for any token list for any spender /// @param tokens array of tokens /// @param spender spender function setTokenApprovals( address[] calldata tokens, address spender ) external; /// @dev sets lending fee with WEI_PERCENT_PRECISION /// @param newValue lending fee percent function setLendingFeePercent(uint256 newValue) external; /// @dev sets trading fee with WEI_PERCENT_PRECISION /// @param newValue trading fee percent function setTradingFeePercent(uint256 newValue) external; /// @dev sets borrowing fee with WEI_PERCENT_PRECISION /// @param newValue borrowing fee percent function setBorrowingFeePercent(uint256 newValue) external; /// @dev sets affiliate fee with WEI_PERCENT_PRECISION /// @param newValue affiliate fee percent function setAffiliateFeePercent(uint256 newValue) external; /// @dev sets liquidation inncetive percent per loan per token. This is the profit percent /// that liquidator gets in the process of liquidating. /// @param loanTokens array list of loan tokens /// @param collateralTokens array list of collateral tokens /// @param amounts array list of liquidation inncetive amount function setLiquidationIncentivePercent( address[] calldata loanTokens, address[] calldata collateralTokens, uint256[] calldata amounts ) external; /// @dev sets max swap rate slippage percent. /// @param newAmount max swap rate slippage percent. function setMaxDisagreement(uint256 newAmount) external; /// TODO function setSourceBufferPercent(uint256 newAmount) external; /// @dev sets maximum supported swap size in ETH /// @param newAmount max swap size in ETH. function setMaxSwapSize(uint256 newAmount) external; /// @dev sets fee controller address /// @param newController address of the new fees controller function setFeesController(address newController) external; /// @dev withdraws lending fees to receiver. Only can be called by feesController address /// @param tokens array of token addresses. /// @param receiver fees receiver address /// @return amounts array of amounts withdrawn function withdrawFees( address[] calldata tokens, address receiver, FeeClaimType feeType ) external returns (uint256[] memory amounts); /// @dev withdraw protocol token (BZRX) from vesting contract vBZRX /// @param receiver address of BZRX tokens claimed /// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance. /// @return rewardToken reward token address /// @return withdrawAmount amount function withdrawProtocolToken(address receiver, uint256 amount) external returns (address rewardToken, uint256 withdrawAmount); /// @dev depozit protocol token (BZRX) /// @param amount address of BZRX tokens to deposit function depositProtocolToken(uint256 amount) external; function grantRewards(address[] calldata users, uint256[] calldata amounts) external returns (uint256 totalAmount); // NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input function queryFees(address[] calldata tokens, FeeClaimType feeType) external view returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid); function priceFeeds() external view returns (address); function swapsImpl() external view returns (address); function logicTargets(bytes4) external view returns (address); function loans(bytes32) external view returns (Loan memory); function loanParams(bytes32) external view returns (LoanParams memory); // we don't use this yet // function lenderOrders(address, bytes32) external returns (Order memory); // function borrowerOrders(address, bytes32) external returns (Order memory); function delegatedManagers(bytes32, address) external view returns (bool); function lenderInterest(address, address) external view returns (LenderInterest memory); function loanInterest(bytes32) external view returns (LoanInterest memory); function feesController() external view returns (address); function lendingFeePercent() external view returns (uint256); function lendingFeeTokensHeld(address) external view returns (uint256); function lendingFeeTokensPaid(address) external view returns (uint256); function borrowingFeePercent() external view returns (uint256); function borrowingFeeTokensHeld(address) external view returns (uint256); function borrowingFeeTokensPaid(address) external view returns (uint256); function protocolTokenHeld() external view returns (uint256); function protocolTokenPaid() external view returns (uint256); function affiliateFeePercent() external view returns (uint256); function liquidationIncentivePercent(address, address) external view returns (uint256); function loanPoolToUnderlying(address) external view returns (address); function underlyingToLoanPool(address) external view returns (address); function supportedTokens(address) external view returns (bool); function maxDisagreement() external view returns (uint256); function sourceBufferPercent() external view returns (uint256); function maxSwapSize() external view returns (uint256); /// @dev get list of loan pools in the system. Ordering is not guaranteed /// @param start start index /// @param count number of pools to return /// @return loanPoolsList array of loan pools function getLoanPoolsList(uint256 start, uint256 count) external view returns (address[] memory loanPoolsList); /// @dev checks whether addreess is a loan pool address /// @return boolean function isLoanPool(address loanPool) external view returns (bool); ////// Loan Settings ////// /// @dev creates new loan param settings /// @param loanParamsList array of LoanParams /// @return loanParamsIdList array of loan ids created function setupLoanParams(LoanParams[] calldata loanParamsList) external returns (bytes32[] memory loanParamsIdList); /// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected. /// @param loanParamsIdList array of loan ids function disableLoanParams(bytes32[] calldata loanParamsIdList) external; /// @dev gets array of LoanParams by given ids /// @param loanParamsIdList array of loan ids /// @return loanParamsList array of LoanParams function getLoanParams(bytes32[] calldata loanParamsIdList) external view returns (LoanParams[] memory loanParamsList); /// @dev Enumerates LoanParams in the system by owner /// @param owner of the loan params /// @param start number of loans to return /// @param count total number of the items /// @return loanParamsList array of LoanParams function getLoanParamsList( address owner, uint256 start, uint256 count ) external view returns (bytes32[] memory loanParamsList); /// @dev returns total loan principal for token address /// @param lender address /// @param loanToken address /// @return total principal of the loan function getTotalPrincipal(address lender, address loanToken) external view returns (uint256); /// @dev returns total principal for a loan pool that was last settled /// @param pool address /// @return total stored principal of the loan function getPoolPrincipalStored(address pool) external view returns (uint256); /// @dev returns the last interest rate founnd during interest settlement /// @param pool address /// @return the last interset rate function getPoolLastInterestRate(address pool) external view returns (uint256); ////// Loan Openings ////// /// @dev This is THE function that borrows or trades on the protocol /// @param loanParamsId id of the LoanParam created beforehand by setupLoanParams function /// @param loanId id of existing loan, if 0, start a new loan /// @param isTorqueLoan boolean whether it is toreque or non torque loan /// @param initialMargin in WEI_PERCENT_PRECISION /// @param sentAddresses array of size 4: /// lender: must match loan if loanId provided /// borrower: must match loan if loanId provided /// receiver: receiver of funds (address(0) assumes borrower address) /// manager: delegated manager of loan unless address(0) /// @param sentValues array of size 5: /// newRate: new loan interest rate /// newPrincipal: new loan size (borrowAmount + any borrowed interest) /// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length) /// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans) /// collateralTokenReceived: total collateralToken deposit /// @param loanDataBytes required when sending ether /// @return principal of the loan and collateral amount function borrowOrTradeFromPool( bytes32 loanParamsId, bytes32 loanId, bool isTorqueLoan, uint256 initialMargin, address[4] calldata sentAddresses, uint256[5] calldata sentValues, bytes calldata loanDataBytes ) external payable returns (LoanOpenData memory); /// @dev sets/disables/enables the delegated manager for the loan /// @param loanId id of the loan /// @param delegated delegated manager address /// @param toggle boolean set enabled or disabled function setDelegatedManager( bytes32 loanId, address delegated, bool toggle ) external; /// @dev estimates margin exposure for simulated position /// @param loanToken address of the loan token /// @param collateralToken address of collateral token /// @param loanTokenSent amout of loan token sent /// @param collateralTokenSent amount of collateral token sent /// @param interestRate yearly interest rate /// @param newPrincipal principal amount of the loan /// @return estimated margin exposure amount function getEstimatedMarginExposure( address loanToken, address collateralToken, uint256 loanTokenSent, uint256 collateralTokenSent, uint256 interestRate, uint256 newPrincipal ) external view returns (uint256); /// @dev calculates required collateral for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param newPrincipal principal amount of the loan /// @param marginAmount margin amount of the loan /// @param isTorqueLoan boolean torque or non torque loan /// @return collateralAmountRequired amount required function getRequiredCollateral( address loanToken, address collateralToken, uint256 newPrincipal, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 collateralAmountRequired); function getRequiredCollateralByParams( bytes32 loanParamsId, uint256 newPrincipal ) external view returns (uint256 collateralAmountRequired); /// @dev calculates borrow amount for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param collateralTokenAmount amount of collateral token sent /// @param marginAmount margin amount /// @param isTorqueLoan boolean torque or non torque loan /// @return borrowAmount possible borrow amount function getBorrowAmount( address loanToken, address collateralToken, uint256 collateralTokenAmount, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 borrowAmount); function getBorrowAmountByParams( bytes32 loanParamsId, uint256 collateralTokenAmount ) external view returns (uint256 borrowAmount); ////// Loan Closings ////// /// @dev liquidates unhealty loans /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount amount of the collateral token of the loan /// @return seizedAmount sezied amount in the collateral token /// @return seizedToken loan token address function liquidate( bytes32 loanId, address receiver, uint256 closeAmount ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param depositAmount amount of loan token to deposit /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDeposit( bytes32 loanId, address receiver, uint256 depositAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param swapAmount amount of loan token to swap /// @param returnTokenIsCollateral boolean whether to return tokens is collateral /// @param loanDataBytes custom payload for specifying swap implementation and data to pass /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwap( bytes32 loanId, address receiver, uint256 swapAmount, // denominated in collateralToken bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Closings With Gas Token ////// /// @dev liquidates unhealty loans by using Gas token /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param gasTokenUser user address of the GAS token /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount loan close amount /// @return seizedAmount loan token withdraw amount /// @return seizedToken loan token address function liquidateWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 closeAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param depositAmount amount of loan token to deposit denominated in loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDepositWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 depositAmount ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param swapAmount amount of loan token to swap denominated in collateralToken /// @param returnTokenIsCollateral true: withdraws collateralToken, false: withdraws loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwapWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 swapAmount, bool returnTokenIsCollateral, bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Maintenance ////// /// @dev deposit collateral to existing loan /// @param loanId existing loan id /// @param depositAmount amount to deposit which must match msg.value if ether is sent function depositCollateral(bytes32 loanId, uint256 depositAmount) external payable; /// @dev withdraw collateral from existing loan /// @param loanId existing loan id /// @param receiver address of withdrawn tokens /// @param withdrawAmount amount to withdraw /// @return actualWithdrawAmount actual amount withdrawn function withdrawCollateral( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 actualWithdrawAmount); /// @dev settles accrued interest for all active loans from a loan pool /// @param loanId existing loan id function settleInterest(bytes32 loanId) external; /*/// @dev withdraw accrued interest rate for a loan given token address /// @param loanToken loan token address function withdrawAccruedInterest(address loanToken) external;*/ /*/// @dev extends loan duration by depositing more collateral /// @param loanId id of the existing loan /// @param depositAmount amount to deposit /// @param useCollateral boolean whether to extend using collateral or deposit amount /// @return secondsExtended by that number of seconds loan duration was extended function extendLoanDuration( bytes32 loanId, uint256 depositAmount, bool useCollateral, bytes calldata // for future use loanDataBytes ) external payable returns (uint256 secondsExtended);*/ /*/// @dev reduces loan duration by withdrawing collateral /// @param loanId id of the existing loan /// @param receiver address to receive tokens /// @param withdrawAmount amount to withdraw /// @return secondsReduced by that number of seconds loan duration was extended function reduceLoanDuration( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 secondsReduced);*/ function setDepositAmount( bytes32 loanId, uint256 depositValueAsLoanToken, uint256 depositValueAsCollateralToken ) external; function claimRewards(address receiver) external returns (uint256 claimAmount); function transferLoan(bytes32 loanId, address newOwner) external; function rewardsBalanceOf(address user) external view returns (uint256 rewardsBalance); function getInterestModelValues( address pool, bytes32 loanId) external view returns ( uint256 _poolLastUpdateTime, uint256 _poolPrincipalTotal, uint256 _poolInterestTotal, uint256 _poolRatePerTokenStored, uint256 _poolLastInterestRate, uint256 _loanPrincipalTotal, uint256 _loanInterestTotal, uint256 _loanRatePerTokenPaid ); /*/// @dev Gets current lender interest data totals for all loans with a specific oracle and interest token /// @param lender The lender address /// @param loanToken The loan token address /// @return interestPaid The total amount of interest that has been paid to a lender so far /// @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet /// @return interestOwedPerDay The amount of interest the lender is earning per day /// @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn /// @return interestFeePercent The fee retained by the protocol before interest is paid to the lender /// @return principalTotal The total amount of outstading principal the lender has loaned function getLenderInterestData(address lender, address loanToken) external view returns ( uint256 interestPaid, uint256 interestPaidDate, uint256 interestOwedPerDay, uint256 interestUnPaid, uint256 interestFeePercent, uint256 principalTotal ); /// @dev Gets current interest data for a loan /// @param loanId A unique id representing the loan /// @return loanToken The loan token that interest is paid in /// @return interestOwedPerDay The amount of interest the borrower is paying per day /// @return interestDepositTotal The total amount of interest the borrower has deposited /// @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender function getLoanInterestData(bytes32 loanId) external view returns ( address loanToken, uint256 interestOwedPerDay, uint256 interestDepositTotal, uint256 interestDepositRemaining );*/ /// @dev gets list of loans of particular user address /// @param user address of the loans /// @param start of the index /// @param count number of loans to return /// @param loanType type of the loan: All(0), Margin(1), NonMargin(2) /// @param isLender whether to list lender loans or borrower loans /// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation /// @return loansData LoanReturnData array of loans function getUserLoans( address user, uint256 start, uint256 count, LoanType loanType, bool isLender, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); function getUserLoansCount(address user, bool isLender) external view returns (uint256); /// @dev gets existing loan /// @param loanId id of existing loan /// @return loanData array of loans function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData); /// @dev gets loan principal including interest /// @param loanId id of existing loan /// @return principal function getLoanPrincipal(bytes32 loanId) external view returns (uint256 principal); /// @dev gets loan outstanding interest /// @param loanId id of existing loan /// @return interest function getLoanInterestOutstanding(bytes32 loanId) external view returns (uint256 interest); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) function getActiveLoans( uint256 start, uint256 count, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) /// @param isLiquidatable boolean if true return liquidatable loans only function getActiveLoansAdvanced( uint256 start, uint256 count, bool unsafeOnly, bool isLiquidatable ) external view returns (LoanReturnData[] memory loansData); function getActiveLoansCount() external view returns (uint256); ////// Swap External ////// /// @dev swap thru external integration /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternal( address sourceToken, address destToken, address receiver, address returnToSender, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev swap thru external integration using GAS /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param gasTokenUser user address of the GAS token /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternalWithGasToken( address sourceToken, address destToken, address receiver, address returnToSender, address gasTokenUser, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev calculate simulated return of swap /// @param sourceToken source token address /// @param destToken destination token address /// @param sourceTokenAmount source token amount /// @return amoun denominated in destination token function getSwapExpectedReturn( address sourceToken, address destToken, uint256 sourceTokenAmount, bytes calldata swapData ) external view returns (uint256); function owner() external view returns (address); function transferOwnership(address newOwner) external; /// Guardian Interface function _isPaused(bytes4 sig) external view returns (bool isPaused); function toggleFunctionPause(bytes4 sig) external; function toggleFunctionUnPause(bytes4 sig) external; function changeGuardian(address newGuardian) external; function getGuardian() external view returns (address guardian); /// Loan Cleanup Interface function cleanupLoans( address loanToken, bytes32[] calldata loanIds) external payable returns (uint256 totalPrincipalIn); struct LoanParams { bytes32 id; bool active; address owner; address loanToken; address collateralToken; uint256 minInitialMargin; uint256 maintenanceMargin; uint256 maxLoanTerm; } struct LoanOpenData { bytes32 loanId; uint256 principal; uint256 collateral; } enum LoanType { All, Margin, NonMargin } struct LoanReturnData { bytes32 loanId; uint96 endTimestamp; address loanToken; address collateralToken; uint256 principal; uint256 collateral; uint256 interestOwedPerDay; uint256 interestDepositRemaining; uint256 startRate; uint256 startMargin; uint256 maintenanceMargin; uint256 currentMargin; uint256 maxLoanTerm; uint256 maxLiquidatable; uint256 maxSeizable; uint256 depositValueAsLoanToken; uint256 depositValueAsCollateralToken; } enum FeeClaimType { All, Lending, Trading, Borrowing } struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset uint256 owedPerDay; // interest owed per day for all loans of asset uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term) uint256 paidTotal; // total interest paid so far for asset uint256 updatedTimestamp; // last update } struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan uint256 depositTotal; // total escrowed interest for loan uint256 updatedTimestamp; // last update } ////// Flash Borrow Fees ////// function payFlashBorrowFees( address user, uint256 borrowAmount, uint256 flashBorrowFeePercent) external; } // Part: IBridge interface IBridge { function send( address _receiver, address _token, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage ) external; function relay( bytes calldata _relayRequest, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external; function transfers(bytes32 transferId) external view returns (bool); function withdraws(bytes32 withdrawId) external view returns (bool); function withdraw( bytes calldata _wdmsg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external; /** * @notice Verifies that a message is signed by a quorum among the signers. * @param _msg signed message * @param _sigs list of signatures sorted by signer addresses in ascending order * @param _signers sorted list of current signers * @param _powers powers of current signers */ function verifySigs( bytes memory _msg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external view; } // Part: ICurve3Pool interface ICurve3Pool { function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 token_amount, int128 i, uint256 min_amount ) external; function get_virtual_price() external view returns (uint256); } // Part: IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: IPriceFeeds interface IPriceFeeds { function queryRate( address sourceToken, address destToken) external view returns (uint256 rate, uint256 precision); function queryReturn( address sourceToken, address destToken, uint256 sourceAmount) external view returns (uint256 destAmount); } // Part: IStakingV2 interface IStakingV2 { struct ProposalState { uint256 proposalTime; uint256 iOOKIWeight; uint256 lpOOKIBalance; uint256 lpTotalSupply; } struct AltRewardsUserInfo { uint256 rewardsPerShare; uint256 pendingRewards; } function getCurrentFeeTokens() external view returns (address[] memory); function maxUniswapDisagreement() external view returns (uint256); function fundsWallet() external view returns (address); function callerRewardDivisor() external view returns (uint256); function maxCurveDisagreement() external view returns (uint256); function rewardPercent() external view returns (uint256); function addRewards(uint256 newOOKI, uint256 newStableCoin) external; function stake(address[] calldata tokens, uint256[] calldata values) external; function unstake(address[] calldata tokens, uint256[] calldata values) external; function earned(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function pendingCrvRewards(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function getVariableWeights() external view returns ( uint256 vBZRXWeight, uint256 iOOKIWeight, uint256 LPTokenWeight ); function balanceOfByAsset(address token, address account) external view returns (uint256 balance); function balanceOfByAssets(address account) external view returns ( uint256 bzrxBalance, uint256 iOOKIBalance, uint256 vBZRXBalance, uint256 LPTokenBalance ); function balanceOfStored(address account) external view returns (uint256 vestedBalance, uint256 vestingBalance); function totalSupplyStored() external view returns (uint256 supply); function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime ) external view returns (uint256 vested); function votingBalanceOf(address account, uint256 proposalId) external view returns (uint256 totalVotes); function votingBalanceOfNow(address account) external view returns (uint256 totalVotes); function votingFromStakedBalanceOf(address account) external view returns (uint256 totalVotes); function _setProposalVals(address account, uint256 proposalId) external returns (uint256); function exit() external; function addAltRewards(address token, uint256 amount) external; function governor() external view returns (address); function owner() external view returns (address); function transferOwnership(address newOwner) external; function claim(bool restake) external; function claimAltRewards() external; function _totalSupplyPerToken(address) external view returns(uint256); /// Guardian Interface function _isPaused(bytes4 sig) external view returns (bool isPaused); function toggleFunctionPause(bytes4 sig) external; function toggleFunctionUnPause(bytes4 sig) external; function changeGuardian(address newGuardian) external; function getGuardian() external view returns (address guardian); // Admin functions // Withdraw all from sushi masterchef function exitSushi() external; function setGovernor(address _governor) external; function setApprovals( address _token, address _spender, uint256 _value ) external; function setVoteDelegator(address stakingGovernance) external; function updateSettings(address settingsTarget, bytes calldata callData) external; function claimSushi() external returns (uint256 sushiRewardsEarned); function totalSupplyByAsset(address token) external view returns (uint256); function vestingLastSync(address user) external view returns(uint256); } // Part: IUniswapV2Router interface IUniswapV2Router { // 0x38ed1739 function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x8803dbee function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x1f00ca74 function getAmountsIn( uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); // 0xd06ca61f function getAmountsOut( uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: Ownable /** * @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); } } // Part: SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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"); } } } // Part: PausableGuardian_0_8 contract PausableGuardian_0_8 is Ownable { // keccak256("Pausable_FunctionPause") bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; // keccak256("Pausable_GuardianAddress") bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf; modifier pausable() { require(!_isPaused(msg.sig) || msg.sender == getGuardian(), "paused"); _; } function _isPaused(bytes4 sig) public view returns (bool isPaused) { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { isPaused := sload(slot) } } function toggleFunctionPause(bytes4 sig) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 1) } } function toggleFunctionUnPause(bytes4 sig) public { // only DAO can unpause, and adding guardian temporarily require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 0) } } function changeGuardian(address newGuardian) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); assembly { sstore(Pausable_GuardianAddress, newGuardian) } } function getGuardian() public view returns (address guardian) { assembly { guardian := sload(Pausable_GuardianAddress) } } } // File: FeeExtractAndDistribute_ETH.sol contract FeeExtractAndDistribute_ETH is PausableGuardian_0_8 { using SafeERC20 for IERC20; address public implementation; IStakingV2 public constant STAKING = IStakingV2(0x16f179f5C344cc29672A58Ea327A26F64B941a63); address public constant OOKI = 0x0De05F6447ab4D22c8827449EE4bA2D5C288379B; IERC20 public constant CURVE_3CRV = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant BUYBACK = 0x12EBd8263A54751Aaf9d8C2c74740A8e62C0AfBe; address public constant BRIDGE = 0x5427FEFA711Eff984124bFBB1AB6fbf5E3DA1820; uint64 public constant DEST_CHAINID = 137; //polygon IUniswapV2Router public constant UNISWAP_ROUTER = IUniswapV2Router(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // sushiswap ICurve3Pool public constant CURVE_3POOL = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); IBZx public constant BZX = IBZx(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f); mapping(address => address[]) public swapPaths; mapping(address => uint256) public stakingRewards; address[] public feeTokens; uint256 public buybackPercent; event ExtractAndDistribute(); event WithdrawFees(address indexed sender); event DistributeFees( address indexed sender, uint256 bzrxRewards, uint256 stableCoinRewards ); event ConvertFees( address indexed sender, uint256 bzrxOutput, uint256 stableCoinOutput ); // Fee Conversion Logic // function sweepFees() public pausable returns (uint256 bzrxRewards, uint256 crv3Rewards) { uint256[] memory amounts = _withdrawFees(feeTokens); _convertFees(feeTokens, amounts); (bzrxRewards, crv3Rewards) = _distributeFees(); } function sweepFees(address[] memory assets) public pausable returns (uint256 bzrxRewards, uint256 crv3Rewards) { uint256[] memory amounts = _withdrawFees(assets); _convertFees(assets, amounts); (bzrxRewards, crv3Rewards) = _distributeFees(); } function _withdrawFees(address[] memory assets) internal returns (uint256[] memory) { uint256[] memory amounts = BZX.withdrawFees( assets, address(this), IBZx.FeeClaimType.All ); for (uint256 i = 0; i < assets.length; i++) { stakingRewards[assets[i]] += amounts[i]; } emit WithdrawFees(msg.sender); return amounts; } function _convertFees(address[] memory assets, uint256[] memory amounts) internal returns (uint256 bzrxOutput, uint256 crv3Output) { require(assets.length == amounts.length, "count mismatch"); IPriceFeeds priceFeeds = IPriceFeeds(BZX.priceFeeds()); //(uint256 bzrxRate, ) = priceFeeds.queryRate(OOKI, WETH); uint256 maxDisagreement = 1e18; address asset; uint256 daiAmount; uint256 usdcAmount; uint256 usdtAmount; for (uint256 i = 0; i < assets.length; i++) { asset = assets[i]; if (asset == OOKI) { continue; } else if (asset == DAI) { daiAmount += amounts[i]; continue; } else if (asset == USDC) { usdcAmount += amounts[i]; continue; } else if (asset == USDT) { usdtAmount += amounts[i]; continue; } if (amounts[i] != 0) { bzrxOutput += _convertFeeWithUniswap( asset, amounts[i], priceFeeds, 0, /*bzrxRate*/ maxDisagreement ); } } if (bzrxOutput != 0) { stakingRewards[OOKI] += bzrxOutput; } if (daiAmount != 0 || usdcAmount != 0 || usdtAmount != 0) { crv3Output = _convertFeesWithCurve( daiAmount, usdcAmount, usdtAmount ); stakingRewards[address(CURVE_3CRV)] += crv3Output; } emit ConvertFees(msg.sender, bzrxOutput, crv3Output); } function _distributeFees() internal returns (uint256 bzrxRewards, uint256 crv3Rewards) { bzrxRewards = stakingRewards[OOKI]; crv3Rewards = stakingRewards[address(CURVE_3CRV)]; uint256 USDCBridge = 0; if (bzrxRewards != 0 || crv3Rewards != 0) { address _fundsWallet = 0xfedC4dD5247B93feb41e899A09C44cFaBec29Cbc; uint256 rewardAmount; uint256 callerReward; uint256 bridgeRewards; if (bzrxRewards != 0) { stakingRewards[OOKI] = 0; callerReward = bzrxRewards / 100; IERC20(OOKI).transfer(msg.sender, callerReward); bzrxRewards = bzrxRewards - (callerReward); bridgeRewards = (bzrxRewards * (buybackPercent)) / (1e20); USDCBridge = _convertToUSDCUniswap(bridgeRewards); rewardAmount = (bzrxRewards * (50e18)) / (1e20); IERC20(OOKI).transfer( _fundsWallet, bzrxRewards - rewardAmount - bridgeRewards ); bzrxRewards = rewardAmount; } if (crv3Rewards != 0) { stakingRewards[address(CURVE_3CRV)] = 0; callerReward = crv3Rewards / 100; CURVE_3CRV.transfer(msg.sender, callerReward); crv3Rewards = crv3Rewards - (callerReward); bridgeRewards = (crv3Rewards * (buybackPercent)) / (1e20); USDCBridge += _convertToUSDCCurve(bridgeRewards); rewardAmount = (crv3Rewards * (50e18)) / (1e20); CURVE_3CRV.transfer( _fundsWallet, crv3Rewards - rewardAmount - bridgeRewards ); crv3Rewards = rewardAmount; } STAKING.addRewards(bzrxRewards, crv3Rewards); _bridgeFeesToPolygon(USDCBridge); } emit DistributeFees(msg.sender, bzrxRewards, crv3Rewards); } function _bridgeFeesToPolygon(uint256 bridgeAmount) internal { IBridge(BRIDGE).send( BUYBACK, USDC, bridgeAmount, DEST_CHAINID, uint64(block.timestamp), 10000 ); } function _convertToUSDCUniswap(uint256 amount) internal returns (uint256 returnAmount) { address[] memory path = new address[](3); path[0] = OOKI; path[1] = WETH; path[2] = USDC; uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amount, 1, // amountOutMin path, address(this), block.timestamp ); returnAmount = amounts[amounts.length - 1]; IPriceFeeds priceFeeds = IPriceFeeds(BZX.priceFeeds()); //(uint256 bzrxRate, ) = priceFeeds.queryRate(OOKI, WETH); /*_checkUniDisagreement( OOKI, USDC, amount, returnAmount, STAKING.maxUniswapDisagreement() );*/ } function _convertFeeWithUniswap( address asset, uint256 amount, IPriceFeeds priceFeeds, uint256 bzrxRate, uint256 maxDisagreement ) internal returns (uint256 returnAmount) { uint256 stakingReward = stakingRewards[asset]; if (stakingReward != 0) { if (amount > stakingReward) { amount = stakingReward; } stakingRewards[asset] = stakingReward - (amount); uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amount, 1, // amountOutMin swapPaths[asset], address(this), block.timestamp ); returnAmount = amounts[amounts.length - 1]; // will revert if disagreement found /*_checkUniDisagreement( asset, OOKI, amount, returnAmount, maxDisagreement );*/ } } function _convertToUSDCCurve(uint256 amount) internal returns (uint256 returnAmount) { uint256 beforeBalance = IERC20(USDC).balanceOf(address(this)); CURVE_3POOL.remove_liquidity_one_coin(amount, 1, 1); //does not need to be checked for disagreement as liquidity add handles that returnAmount = IERC20(USDC).balanceOf(address(this)) - beforeBalance; //does not underflow as USDC is not being transferred out } function _convertFeesWithCurve( uint256 daiAmount, uint256 usdcAmount, uint256 usdtAmount ) internal returns (uint256 returnAmount) { uint256[3] memory curveAmounts; uint256 curveTotal; uint256 stakingReward; if (daiAmount != 0) { stakingReward = stakingRewards[DAI]; if (stakingReward != 0) { if (daiAmount > stakingReward) { daiAmount = stakingReward; } stakingRewards[DAI] = stakingReward - (daiAmount); curveAmounts[0] = daiAmount; curveTotal = daiAmount; } } if (usdcAmount != 0) { stakingReward = stakingRewards[USDC]; if (stakingReward != 0) { if (usdcAmount > stakingReward) { usdcAmount = stakingReward; } stakingRewards[USDC] = stakingReward - (usdcAmount); curveAmounts[1] = usdcAmount; curveTotal += usdcAmount * 1e12; // normalize to 18 decimals } } if (usdtAmount != 0) { stakingReward = stakingRewards[USDT]; if (stakingReward != 0) { if (usdtAmount > stakingReward) { usdtAmount = stakingReward; } stakingRewards[USDT] = stakingReward - (usdtAmount); curveAmounts[2] = usdtAmount; curveTotal += usdtAmount * 1e12; // normalize to 18 decimals } } uint256 beforeBalance = CURVE_3CRV.balanceOf(address(this)); CURVE_3POOL.add_liquidity( curveAmounts, (curveTotal * 1e18 / CURVE_3POOL.get_virtual_price())*995/1000 ); returnAmount = CURVE_3CRV.balanceOf(address(this)) - beforeBalance; } function _checkUniDisagreement( address asset, address recvAsset, uint256 assetAmount, uint256 recvAmount, uint256 maxDisagreement ) internal view { uint256 estAmountOut = IPriceFeeds(BZX.priceFeeds()).queryReturn( asset, recvAsset, assetAmount ); uint256 spreadValue = estAmountOut > recvAmount ? estAmountOut - recvAmount : recvAmount - estAmountOut; if (spreadValue != 0) { spreadValue = (spreadValue * 1e20) / estAmountOut; require( spreadValue <= maxDisagreement, "uniswap price disagreement" ); } } function setApprovals() external onlyOwner { IERC20(DAI).safeApprove(address(CURVE_3POOL), type(uint256).max); IERC20(USDC).safeApprove(address(CURVE_3POOL), type(uint256).max); IERC20(USDC).safeApprove(BRIDGE, type(uint256).max); IERC20(USDT).safeApprove(address(CURVE_3POOL), 0); IERC20(USDT).safeApprove(address(CURVE_3POOL), type(uint256).max); IERC20(OOKI).safeApprove(address(STAKING), type(uint256).max); IERC20(OOKI).safeApprove(address(UNISWAP_ROUTER), type(uint256).max); CURVE_3CRV.safeApprove(address(STAKING), type(uint256).max); } // path should start with the asset to swap and end with OOKI // only one path allowed per asset // ex: asset -> WETH -> OOKI function setPaths(address[][] calldata paths) external onlyOwner { address[] memory path; for (uint256 i = 0; i < paths.length; i++) { path = paths[i]; require( path.length >= 2 && path[0] != path[path.length - 1] && path[path.length - 1] == OOKI, "invalid path" ); // check that the path exists uint256[] memory amountsOut = UNISWAP_ROUTER.getAmountsOut( 1e10, path ); require( amountsOut[amountsOut.length - 1] != 0, "path does not exist" ); swapPaths[path[0]] = path; IERC20(path[0]).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(path[0]).safeApprove(address(UNISWAP_ROUTER), type(uint256).max); } } function setBuybackSettings(uint256 amount) external onlyOwner { buybackPercent = amount; } function setFeeTokens(address[] calldata tokens) external onlyOwner { feeTokens = tokens; } }
Initializes the contract setting the deployer as the initial owner./
function getCurrentFeeTokens() external view returns (address[] memory); function maxUniswapDisagreement() external view returns (uint256); function fundsWallet() external view returns (address); function callerRewardDivisor() external view returns (uint256); function maxCurveDisagreement() external view returns (uint256); function rewardPercent() external view returns (uint256); function addRewards(uint256 newOOKI, uint256 newStableCoin) external; function stake(address[] calldata tokens, uint256[] calldata values) external; function unstake(address[] calldata tokens, uint256[] calldata values) external; function earned(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function pendingCrvRewards(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function getVariableWeights() external view returns ( uint256 vBZRXWeight, uint256 iOOKIWeight, uint256 LPTokenWeight ); function balanceOfByAsset(address token, address account) external view returns (uint256 balance); function balanceOfByAssets(address account) external view returns ( uint256 bzrxBalance, uint256 iOOKIBalance, uint256 vBZRXBalance, uint256 LPTokenBalance ); function balanceOfStored(address account) external view returns (uint256 vestedBalance, uint256 vestingBalance); function totalSupplyStored() external view returns (uint256 supply); function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime ) external view returns (uint256 vested); function votingBalanceOf(address account, uint256 proposalId) external view returns (uint256 totalVotes); function votingBalanceOfNow(address account) external view returns (uint256 totalVotes); function votingFromStakedBalanceOf(address account) external view returns (uint256 totalVotes); function _setProposalVals(address account, uint256 proposalId) external returns (uint256); function exit() external; function addAltRewards(address token, uint256 amount) external; function governor() external view returns (address); function owner() external view returns (address); function transferOwnership(address newOwner) external; function claim(bool restake) external; function claimAltRewards() external; function _totalSupplyPerToken(address) external view returns(uint256); function _isPaused(bytes4 sig) external view returns (bool isPaused); function toggleFunctionPause(bytes4 sig) external; function toggleFunctionUnPause(bytes4 sig) external; function changeGuardian(address newGuardian) external; function getGuardian() external view returns (address guardian); function exitSushi() external; function setGovernor(address _governor) external; function setApprovals( address _token, address _spender, uint256 _value ) external; function setVoteDelegator(address stakingGovernance) external; function updateSettings(address settingsTarget, bytes calldata callData) external; function claimSushi() external returns (uint256 sushiRewardsEarned); function totalSupplyByAsset(address token) external view returns (uint256); function vestingLastSync(address user) external view returns(uint256); } } constructor() { _transferOwnership(_msgSender()); }
11,721,625
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; contract NoReturnTransferTokenMock { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); mapping(address => uint256) internal balances; uint256 internal totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function mint(address _to, uint256 _amount) public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } // solhint-disable-next-line no-simple-event-func-name function transfer(address _to, uint256 _value) public { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); } }
solhint-disable-next-line no-simple-event-func-name
function transfer(address _to, uint256 _value) public { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); }
12,729,259
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; pragma experimental ABIEncoderV2; // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardEvents.sol /// @title Witnet Request Board emitting events interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardEvents { /// Emitted when a Witnet Data Request is posted to the WRB. event PostedRequest(uint256 queryId, address from); /// Emitted when a Witnet-solved result is reported to the WRB. event PostedResult(uint256 queryId, address from); /// Emitted when all data related to given query is deleted from the WRB. event DeletedQuery(uint256 queryId, address from); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardReporter.sol /// @title The Witnet Request Board Reporter interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardReporter { /// Reports the Witnet-provided result to a previously posted request. /// @dev Will assume `block.timestamp` as the timestamp at which the request was solved. /// @dev Fails if: /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique identifier of the data request. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, bytes32 _drTxHash, bytes calldata _result) external; /// Reports the Witnet-provided result to a previously posted request. /// @dev Fails if: /// @dev - called from unauthorized address; /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique query identifier /// @param _timestamp The timestamp of the solving tally transaction in Witnet. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, uint256 _timestamp, bytes32 _drTxHash, bytes calldata _result) external; } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequest.sol /// @title The Witnet Data Request basic interface. /// @author The Witnet Foundation. interface IWitnetRequest { /// A `IWitnetRequest` is constructed around a `bytes` value containing /// a well-formed Witnet Data Request using Protocol Buffers. function bytecode() external view returns (bytes memory); /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. function hash() external view returns (bytes32); } // File: node_modules\witnet-solidity-bridge\contracts\libs\Witnet.sol library Witnet { /// @notice Witnet function that computes the hash of a CBOR-encoded Data Request. /// @param _bytecode CBOR-encoded RADON. function hash(bytes memory _bytecode) internal pure returns (bytes32) { return sha256(_bytecode); } /// Struct containing both request and response data related to every query posted to the Witnet Request Board struct Query { Request request; Response response; } /// Possible status of a Witnet query. enum QueryStatus { Unknown, Posted, Reported, Deleted } /// Data kept in EVM-storage for every Request posted to the Witnet Request Board. struct Request { IWitnetRequest addr; // The contract containing the Data Request which execution has been requested. address requester; // Address from which the request was posted. bytes32 hash; // Hash of the Data Request whose execution has been requested. uint256 gasprice; // Minimum gas price the DR resolver should pay on the solving tx. uint256 reward; // Escrowed reward to be paid to the DR resolver. } /// Data kept in EVM-storage containing Witnet-provided response metadata and result. struct Response { address reporter; // Address from which the result was reported. uint256 timestamp; // Timestamp of the Witnet-provided result. bytes32 drTxHash; // Hash of the Witnet transaction that solved the queried Data Request. bytes cborBytes; // Witnet-provided result CBOR-bytes to the queried Data Request. } /// Data struct containing the Witnet-provided result to a Data Request. struct Result { bool success; // Flag stating whether the request could get solved successfully, or not. CBOR value; // Resulting value, in CBOR-serialized bytes. } /// Data struct following the RFC-7049 standard: Concise Binary Object Representation. struct CBOR { Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /// Iterable bytes buffer. struct Buffer { bytes data; uint32 cursor; } /// Witnet error codes table. enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid Data Request. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, /// Unallocated Math0x43, Math0x44, Math0x45, Math0x46, Math0x47, Math0x48, Math0x49, Math0x4A, Math0x4B, Math0x4C, Math0x4D, Math0x4E, Math0x4F, // Other errors /// 0x50: Received zero reveals NoReveals, /// 0x51: Insufficient consensus in tally precondition clause InsufficientConsensus, /// 0x52: Received zero commits InsufficientCommits, /// 0x53: Generic error during tally execution TallyExecution, /// Unallocated OtherError0x54, OtherError0x55, OtherError0x56, OtherError0x57, OtherError0x58, OtherError0x59, OtherError0x5A, OtherError0x5B, OtherError0x5C, OtherError0x5D, OtherError0x5E, OtherError0x5F, /// 0x60: Invalid reveal serialization (malformed reveals are converted to this value) MalformedReveal, /// Unallocated OtherError0x61, OtherError0x62, OtherError0x63, OtherError0x64, OtherError0x65, OtherError0x66, OtherError0x67, OtherError0x68, OtherError0x69, OtherError0x6A, OtherError0x6B, OtherError0x6C, OtherError0x6D, OtherError0x6E, OtherError0x6F, // Access errors /// 0x70: Tried to access a value from an index using an index that is out of bounds ArrayIndexOutOfBounds, /// 0x71: Tried to access a value from a map using a key that does not exist MapKeyNotFound, /// Unallocated OtherError0x72, OtherError0x73, OtherError0x74, OtherError0x75, OtherError0x76, OtherError0x77, OtherError0x78, OtherError0x79, OtherError0x7A, OtherError0x7B, OtherError0x7C, OtherError0x7D, OtherError0x7E, OtherError0x7F, OtherError0x80, OtherError0x81, OtherError0x82, OtherError0x83, OtherError0x84, OtherError0x85, OtherError0x86, OtherError0x87, OtherError0x88, OtherError0x89, OtherError0x8A, OtherError0x8B, OtherError0x8C, OtherError0x8D, OtherError0x8E, OtherError0x8F, OtherError0x90, OtherError0x91, OtherError0x92, OtherError0x93, OtherError0x94, OtherError0x95, OtherError0x96, OtherError0x97, OtherError0x98, OtherError0x99, OtherError0x9A, OtherError0x9B, OtherError0x9C, OtherError0x9D, OtherError0x9E, OtherError0x9F, OtherError0xA0, OtherError0xA1, OtherError0xA2, OtherError0xA3, OtherError0xA4, OtherError0xA5, OtherError0xA6, OtherError0xA7, OtherError0xA8, OtherError0xA9, OtherError0xAA, OtherError0xAB, OtherError0xAC, OtherError0xAD, OtherError0xAE, OtherError0xAF, OtherError0xB0, OtherError0xB1, OtherError0xB2, OtherError0xB3, OtherError0xB4, OtherError0xB5, OtherError0xB6, OtherError0xB7, OtherError0xB8, OtherError0xB9, OtherError0xBA, OtherError0xBB, OtherError0xBC, OtherError0xBD, OtherError0xBE, OtherError0xBF, OtherError0xC0, OtherError0xC1, OtherError0xC2, OtherError0xC3, OtherError0xC4, OtherError0xC5, OtherError0xC6, OtherError0xC7, OtherError0xC8, OtherError0xC9, OtherError0xCA, OtherError0xCB, OtherError0xCC, OtherError0xCD, OtherError0xCE, OtherError0xCF, OtherError0xD0, OtherError0xD1, OtherError0xD2, OtherError0xD3, OtherError0xD4, OtherError0xD5, OtherError0xD6, OtherError0xD7, OtherError0xD8, OtherError0xD9, OtherError0xDA, OtherError0xDB, OtherError0xDC, OtherError0xDD, OtherError0xDE, OtherError0xDF, // Bridge errors: errors that only belong in inter-client communication /// 0xE0: Requests that cannot be parsed must always get this error as their result. /// However, this is not a valid result in a Tally transaction, because invalid requests /// are never included into blocks and therefore never get a Tally in response. BridgeMalformedRequest, /// 0xE1: Witnesses exceeds 100 BridgePoorIncentives, /// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an /// amount of value that is unjustifiably high when compared with the reward they will be getting BridgeOversizedResult, /// Unallocated OtherError0xE3, OtherError0xE4, OtherError0xE5, OtherError0xE6, OtherError0xE7, OtherError0xE8, OtherError0xE9, OtherError0xEA, OtherError0xEB, OtherError0xEC, OtherError0xED, OtherError0xEE, OtherError0xEF, OtherError0xF0, OtherError0xF1, OtherError0xF2, OtherError0xF3, OtherError0xF4, OtherError0xF5, OtherError0xF6, OtherError0xF7, OtherError0xF8, OtherError0xF9, OtherError0xFA, OtherError0xFB, OtherError0xFC, OtherError0xFD, OtherError0xFE, // This should not exist: /// 0xFF: Some tally error is not intercepted but should UnhandledIntercept } } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardRequestor.sol /// @title Witnet Requestor Interface /// @notice It defines how to interact with the Witnet Request Board in order to: /// - request the execution of Witnet Radon scripts (data request); /// - upgrade the resolution reward of any previously posted request, in case gas price raises in mainnet; /// - read the result of any previously posted request, eventually reported by the Witnet DON. /// - remove from storage all data related to past and solved data requests, and results. /// @author The Witnet Foundation. interface IWitnetRequestBoardRequestor { /// Retrieves a copy of all Witnet-provided data related to a previously posted request, removing the whole query from the WRB storage. /// @dev Fails if the `_queryId` is not in 'Reported' status, or called from an address different to /// @dev the one that actually posted the given request. /// @param _queryId The unique query identifier. function deleteQuery(uint256 _queryId) external returns (Witnet.Response memory); /// Requests the execution of the given Witnet Data Request in expectation that it will be relayed and solved by the Witnet DON. /// A reward amount is escrowed by the Witnet Request Board that will be transferred to the reporter who relays back the Witnet-provided /// result to this request. /// @dev Fails if: /// @dev - provided reward is too low. /// @dev - provided script is zero address. /// @dev - provided script bytecode is empty. /// @param _addr The address of the IWitnetRequest contract that can provide the actual Data Request bytecode. /// @return _queryId An unique query identifier. function postRequest(IWitnetRequest _addr) external payable returns (uint256 _queryId); /// Increments the reward of a previously posted request by adding the transaction value to it. /// @dev Updates request `gasPrice` in case this method is called with a higher /// @dev gas price value than the one used in previous calls to `postRequest` or /// @dev `upgradeReward`. /// @dev Fails if the `_queryId` is not in 'Posted' status. /// @dev Fails also in case the request `gasPrice` is increased, and the new /// @dev reward value gets below new recalculated threshold. /// @param _queryId The unique query identifier. function upgradeReward(uint256 _queryId) external payable; } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardView.sol /// @title Witnet Request Board info interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardView { /// Estimates the amount of reward we need to insert for a given gas price. /// @param _gasPrice The gas price for which we need to calculate the rewards. function estimateReward(uint256 _gasPrice) external view returns (uint256); /// Returns next query id to be generated by the Witnet Request Board. function getNextQueryId() external view returns (uint256); /// Gets the whole Query data contents, if any, no matter its current status. function getQueryData(uint256 _queryId) external view returns (Witnet.Query memory); /// Gets current status of given query. function getQueryStatus(uint256 _queryId) external view returns (Witnet.QueryStatus); /// Retrieves the whole `Witnet.Request` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequest(uint256 _queryId) external view returns (Witnet.Request memory); /// Retrieves the serialized bytecode of a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestBytecode(uint256 _queryId) external view returns (bytes memory); /// Retrieves the gas price that any assigned reporter will have to pay when reporting result /// to the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestGasPrice(uint256 _queryId) external view returns (uint256); /// Retrieves the reward currently set for the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestReward(uint256 _queryId) external view returns (uint256); /// Retrieves the whole `Witnet.Response` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponse(uint256 _queryId) external view returns (Witnet.Response memory); /// Retrieves the hash of the Witnet transaction hash that actually solved the referred query. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseDrTxHash(uint256 _queryId) external view returns (bytes32); /// Retrieves the address that reported the result to a previously-posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseReporter(uint256 _queryId) external view returns (address); /// Retrieves the Witnet-provided CBOR-bytes result of a previously posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseResult(uint256 _queryId) external view returns (Witnet.Result memory); /// Retrieves the timestamp in which the result to the referred query was solved by the Witnet DON. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseTimestamp(uint256 _queryId) external view returns (uint256); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestParser.sol /// @title The Witnet interface for decoding Witnet-provided request to Data Requests. /// This interface exposes functions to check for the success/failure of /// a Witnet-provided result, as well as to parse and convert result into /// Solidity types suitable to the application level. /// @author The Witnet Foundation. interface IWitnetRequestParser { /// Decode raw CBOR bytes into a Witnet.Result instance. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.Result` instance. function resultFromCborBytes(bytes memory _cborBytes) external pure returns (Witnet.Result memory); /// Decode a CBOR value into a Witnet.Result instance. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return A `Witnet.Result` instance. function resultFromCborValue(Witnet.CBOR memory _cborValue) external pure returns (Witnet.Result memory); /// Tell if a Witnet.Result is successful. /// @param _result An instance of Witnet.Result. /// @return `true` if successful, `false` if errored. function isOk(Witnet.Result memory _result) external pure returns (bool); /// Tell if a Witnet.Result is errored. /// @param _result An instance of Witnet.Result. /// @return `true` if errored, `false` if successful. function isError(Witnet.Result memory _result) external pure returns (bool); /// Decode a bytes value from a Witnet.Result as a `bytes` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes` decoded from the Witnet.Result. function asBytes(Witnet.Result memory _result) external pure returns (bytes memory); /// Decode a bytes value from a Witnet.Result as a `bytes32` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes32` decoded from the Witnet.Result. function asBytes32(Witnet.Result memory _result) external pure returns (bytes32); /// Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`. /// @param _result An instance of `Witnet.Result`. /// @return The `CBORValue.Error memory` decoded from the Witnet.Result. function asErrorCode(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes); /// Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments. /// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function /// @param _result An instance of `Witnet.Result`. /// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message. function asErrorMessage(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes, string memory); /// Decode a raw error from a `Witnet.Result` as a `uint64[]`. /// @param _result An instance of `Witnet.Result`. /// @return The `uint64[]` raw error as decoded from the `Witnet.Result`. function asRawError(Witnet.Result memory _result) external pure returns(uint64[] memory); /// Decode a boolean value from a Witnet.Result as an `bool` value. /// @param _result An instance of Witnet.Result. /// @return The `bool` decoded from the Witnet.Result. function asBool(Witnet.Result memory _result) external pure returns (bool); /// Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asFixed16(Witnet.Result memory _result) external pure returns (int32); /// Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory); /// Decode a integer numeric value from a Witnet.Result as an `int128` value. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asInt128(Witnet.Result memory _result) external pure returns (int128); /// Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asInt128Array(Witnet.Result memory _result) external pure returns (int128[] memory); /// Decode a string value from a Witnet.Result as a `string` value. /// @param _result An instance of Witnet.Result. /// @return The `string` decoded from the Witnet.Result. function asString(Witnet.Result memory _result) external pure returns (string memory); /// Decode an array of string values from a Witnet.Result as a `string[]` value. /// @param _result An instance of Witnet.Result. /// @return The `string[]` decoded from the Witnet.Result. function asStringArray(Witnet.Result memory _result) external pure returns (string[] memory); /// Decode a natural numeric value from a Witnet.Result as a `uint64` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64` decoded from the Witnet.Result. function asUint64(Witnet.Result memory _result) external pure returns(uint64); /// Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64[]` decoded from the Witnet.Result. function asUint64Array(Witnet.Result memory _result) external pure returns (uint64[] memory); } // File: node_modules\witnet-solidity-bridge\contracts\WitnetRequestBoard.sol /// @title Witnet Request Board functionality base contract. /// @author The Witnet Foundation. abstract contract WitnetRequestBoard is IWitnetRequestBoardEvents, IWitnetRequestBoardReporter, IWitnetRequestBoardRequestor, IWitnetRequestBoardView, IWitnetRequestParser { receive() external payable { revert("WitnetRequestBoard: no transfers accepted"); } } // File: witnet-solidity-bridge\contracts\UsingWitnet.sol /// @title The UsingWitnet contract /// @dev Witnet-aware contracts can inherit from this contract in order to interact with Witnet. /// @author The Witnet Foundation. abstract contract UsingWitnet { WitnetRequestBoard public immutable witnet; /// Include an address to specify the WitnetRequestBoard entry point address. /// @param _wrb The WitnetRequestBoard entry point address. constructor(WitnetRequestBoard _wrb) { require(address(_wrb) != address(0), "UsingWitnet: zero address"); witnet = _wrb; } /// Provides a convenient way for client contracts extending this to block the execution of the main logic of the /// contract until a particular request has been successfully solved and reported by Witnet. modifier witnetRequestSolved(uint256 _id) { require( _witnetCheckResultAvailability(_id), "UsingWitnet: request not solved" ); _; } /// Check if a data request has been solved and reported by Witnet. /// @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. /// parties) before this method returns `true`. /// @param _id The unique identifier of a previously posted data request. /// @return A boolean telling if the request has been already resolved or not. Returns `false` also, if the result was deleted. function _witnetCheckResultAvailability(uint256 _id) internal view virtual returns (bool) { return witnet.getQueryStatus(_id) == Witnet.QueryStatus.Reported; } /// Estimate the reward amount. /// @param _gasPrice The gas price for which we want to retrieve the estimation. /// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one. function _witnetEstimateReward(uint256 _gasPrice) internal view virtual returns (uint256) { return witnet.estimateReward(_gasPrice); } /// Estimates the reward amount, considering current transaction gas price. /// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one. function _witnetEstimateReward() internal view virtual returns (uint256) { return witnet.estimateReward(tx.gasprice); } /// Send a new request to the Witnet network with transaction value as a reward. /// @param _request An instance of `IWitnetRequest` contract. /// @return _id Sequential identifier for the request included in the WitnetRequestBoard. /// @return _reward Current reward amount escrowed by the WRB until a result gets reported. function _witnetPostRequest(IWitnetRequest _request) internal virtual returns (uint256 _id, uint256 _reward) { _reward = _witnetEstimateReward(); _id = witnet.postRequest{value: _reward}(_request); } /// Upgrade the reward for a previously posted request. /// @dev Call to `upgradeReward` function in the WitnetRequestBoard contract. /// @param _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard. /// @return Amount in which the reward has been increased. function _witnetUpgradeReward(uint256 _id) internal virtual returns (uint256) { uint256 _currentReward = witnet.readRequestReward(_id); uint256 _newReward = _witnetEstimateReward(); uint256 _fundsToAdd = 0; if (_newReward > _currentReward) { _fundsToAdd = (_newReward - _currentReward); } witnet.upgradeReward{value: _fundsToAdd}(_id); // Let Request.gasPrice be updated return _fundsToAdd; } /// Read the Witnet-provided result to a previously posted request. /// @param _id The unique identifier of a request that was posted to Witnet. /// @return The result of the request as an instance of `Witnet.Result`. function _witnetReadResult(uint256 _id) internal view virtual returns (Witnet.Result memory) { return witnet.readResponseResult(_id); } /// Retrieves copy of all response data related to a previously posted request, removing the whole query from storage. /// @param _id The unique identifier of a previously posted request. /// @return The Witnet-provided result to the request. function _witnetDeleteQuery(uint256 _id) internal virtual returns (Witnet.Response memory) { return witnet.deleteQuery(_id); } } // File: node_modules\witnet-solidity-bridge\contracts\requests\WitnetRequestBase.sol abstract contract WitnetRequestBase is IWitnetRequest { /// Contains a well-formed Witnet Data Request, encoded using Protocol Buffers. bytes public override bytecode; /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. bytes32 public override hash; } // File: witnet-solidity-bridge\contracts\requests\WitnetRequest.sol contract WitnetRequest is WitnetRequestBase { using Witnet for bytes; constructor(bytes memory _bytecode) { bytecode = _bytecode; hash = _bytecode.hash(); } } // File: ado-contracts\contracts\interfaces\IERC2362.sol /** * @dev EIP2362 Interface for pull oracles * https://github.com/adoracles/EIPs/blob/erc-2362/EIPS/eip-2362.md */ interface IERC2362 { /** * @dev Exposed function pertaining to EIP standards * @param _id bytes32 ID of the query * @return int,uint,uint returns the value, timestamp, and status code of query */ function valueFor(bytes32 _id) external view returns(int256,uint256,uint256); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetPriceRouter.sol /// @title The Witnet Price Router basic interface. /// @dev Guides implementation of price feeds aggregation contracts. /// @author The Witnet Foundation. abstract contract IWitnetPriceRouter is IERC2362 { /// Emitted everytime a currency pair is attached to a new price feed contract /// @dev See https://github.com/adoracles/ADOIPs/blob/main/adoip-0010.md /// @dev to learn how these ids are created. event CurrencyPairSet(bytes32 indexed erc2362ID, IERC165 pricefeed); /// Helper pure function: returns hash of the provided ERC2362-compliant currency pair caption (aka ID). function currencyPairId(string memory) external pure virtual returns (bytes32); /// Returns the ERC-165-compliant price feed contract currently serving /// updates on the given currency pair. function getPriceFeed(bytes32 _erc2362id) external view virtual returns (IERC165); /// Returns human-readable ERC2362-based caption of the currency pair being /// served by the given price feed contract address. /// @dev Should fail if the given price feed contract address is not currently /// @dev registered in the router. function getPriceFeedCaption(IERC165) external view virtual returns (string memory); /// Returns human-readable caption of the ERC2362-based currency pair identifier, if known. function lookupERC2362ID(bytes32 _erc2362id) external view virtual returns (string memory); /// Register a price feed contract that will serve updates for the given currency pair. /// @dev Setting zero address to a currency pair implies that it will not be served any longer. /// @dev Otherwise, should fail if the price feed contract does not support the `IWitnetPriceFeed` interface, /// @dev or if given price feed is already serving another currency pair (within this WitnetPriceRouter instance). function setPriceFeed( IERC165 _pricefeed, uint256 _decimals, string calldata _base, string calldata _quote ) external virtual; /// Returns list of known currency pairs IDs. function supportedCurrencyPairs() external view virtual returns (bytes32[] memory); /// Returns `true` if given pair is currently being served by a compliant price feed contract. function supportsCurrencyPair(bytes32 _erc2362id) external view virtual returns (bool); /// Returns `true` if given price feed contract is currently serving updates to any known currency pair. function supportsPriceFeed(IERC165 _priceFeed) external view virtual returns (bool); } // File: node_modules\@openzeppelin\contracts\utils\Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin\contracts\access\Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetPriceFeed.sol /// @title The Witnet Price Feed basic interface. /// @dev Guides implementation of active price feed polling contracts. /// @author The Witnet Foundation. interface IWitnetPriceFeed { /// Signals that a new price update request is being posted to the Witnet Request Board event PriceFeeding(address indexed from, uint256 queryId, uint256 extraFee); /// Estimates minimum fee amount in native currency to be paid when /// requesting a new price update. /// @dev Actual fee depends on the gas price of the `requestUpdate()` transaction. /// @param _gasPrice Gas price expected to be paid when calling `requestUpdate()` function estimateUpdateFee(uint256 _gasPrice) external view returns (uint256); /// Returns result of the last valid price update request successfully solved by the Witnet oracle. function lastPrice() external view returns (int256); /// Returns the EVM-timestamp when last valid price was reported back from the Witnet oracle. function lastTimestamp() external view returns (uint256); /// Returns tuple containing last valid price and timestamp, as well as status code of latest update /// request that got posted to the Witnet Request Board. /// @return _lastPrice Last valid price reported back from the Witnet oracle. /// @return _lastTimestamp EVM-timestamp of the last valid price. /// @return _lastDrTxHash Hash of the Witnet Data Request that solved the last valid price. /// @return _latestUpdateStatus Status code of the latest update request. function lastValue() external view returns ( int _lastPrice, uint _lastTimestamp, bytes32 _lastDrTxHash, uint _latestUpdateStatus ); /// Returns identifier of the latest update request posted to the Witnet Request Board. function latestQueryId() external view returns (uint256); /// Returns hash of the Witnet Data Request that solved the latest update request. /// @dev Returning 0 while the latest update request remains unsolved. function latestUpdateDrTxHash() external view returns (bytes32); /// Returns error message of latest update request posted to the Witnet Request Board. /// @dev Returning empty string if the latest update request remains unsolved, or /// @dev if it was succesfully solved with no errors. function latestUpdateErrorMessage() external view returns (string memory); /// Returns status code of latest update request posted to the Witnet Request Board: /// @dev Status codes: /// @dev - 200: update request was succesfully solved with no errors /// @dev - 400: update request was solved with errors /// @dev - 404: update request was not solved yet function latestUpdateStatus() external view returns (uint256); /// Returns `true` if latest update request posted to the Witnet Request Board /// has not been solved yet by the Witnet oracle. function pendingUpdate() external view returns (bool); /// Posts a new price update request to the Witnet Request Board. Requires payment of a fee /// that depends on the value of `tx.gasprice`. See `estimateUpdateFee(uint256)`. /// @dev If previous update request was not solved yet, calling this method again allows /// @dev upgrading the update fee if called with a higher `tx.gasprice` value. function requestUpdate() external payable; /// Tells whether this contract implements the interface defined by `interfaceId`. /// @dev See the corresponding https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] /// @dev to learn more about how these ids are created. function supportsInterface(bytes4) external view returns (bool); } // File: @openzeppelin\contracts\utils\Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: witnet-solidity-bridge\contracts\examples\WitnetPriceRouter.sol contract WitnetPriceRouter is IWitnetPriceRouter, Ownable { using Strings for uint256; struct Pair { IERC165 pricefeed; uint256 decimals; string base; string quote; } mapping (bytes32 => Pair) internal __pairs; mapping (address => bytes32) internal __pricefeedId_; bytes32[] internal __supportedCurrencyPairs; // ======================================================================== // --- Implementation of 'IERC2362' --------------------------------------- /// Returns last valid price value and timestamp, as well as status of /// the latest update request that got posted to the Witnet Request Board. /// @dev Fails if the given currency pair is not currently supported. /// @param _erc2362id Price pair identifier as specified in https://github.com/adoracles/ADOIPs/blob/main/adoip-0010.md /// @return _lastPrice Last valid price reported back from the Witnet oracle. /// @return _lastTimestamp EVM-timestamp of the last valid price. /// @return _latestUpdateStatus Status code of latest update request that got posted to the Witnet Request Board: /// - 200: latest update request was succesfully solved with no errors /// - 400: latest update request was solved with errors /// - 404: latest update request is still pending to be solved function valueFor(bytes32 _erc2362id) external view virtual override returns ( int256 _lastPrice, uint256 _lastTimestamp, uint256 _latestUpdateStatus ) { IWitnetPriceFeed _pricefeed = IWitnetPriceFeed(address(getPriceFeed(_erc2362id))); require(address(_pricefeed) != address(0), "WitnetPriceRouter: unsupported currency pair"); (_lastPrice, _lastTimestamp,, _latestUpdateStatus) = _pricefeed.lastValue(); } // ======================================================================== // --- Implementation of 'IWitnetPriceRouter' --------------------------- /// Helper pure function: returns hash of the provided ERC2362-compliant currency pair caption (aka ID). function currencyPairId(string memory _caption) public pure virtual override returns (bytes32) { return keccak256(bytes(_caption)); } /// Returns the ERC-165-compliant price feed contract currently serving /// updates on the given currency pair. function getPriceFeed(bytes32 _erc2362id) public view virtual override returns (IERC165) { return __pairs[_erc2362id].pricefeed; } /// Returns human-readable ERC2362-based caption of the currency pair being /// served by the given price feed contract address. /// @dev Fails if the given price feed contract address is not currently /// @dev registered in the router. function getPriceFeedCaption(IERC165 _pricefeed) public view virtual override returns (string memory) { require(supportsPriceFeed(_pricefeed), "WitnetPriceRouter: unknown"); return lookupERC2362ID(__pricefeedId_[address(_pricefeed)]); } /// Returns human-readable caption of the ERC2362-based currency pair identifier, if known. function lookupERC2362ID(bytes32 _erc2362id) public view virtual override returns (string memory _caption) { Pair storage _pair = __pairs[_erc2362id]; if ( bytes(_pair.base).length > 0 && bytes(_pair.quote).length > 0 ) { _caption = string(abi.encodePacked( "Price-", _pair.base, "/", _pair.quote, "-", _pair.decimals.toString() )); } } /// Register a price feed contract that will serve updates for the given currency pair. /// @dev Setting zero address to a currency pair implies that it will not be served any longer. /// @dev Otherwise, fails if the price feed contract does not support the `IWitnetPriceFeed` interface, /// @dev or if given price feed is already serving another currency pair (within this WitnetPriceRouter instance). function setPriceFeed( IERC165 _pricefeed, uint256 _decimals, string calldata _base, string calldata _quote ) public virtual override onlyOwner { if (address(_pricefeed) != address(0)) { require( _pricefeed.supportsInterface(type(IWitnetPriceFeed).interfaceId), "WitnetPriceRouter: feed contract is not compliant with IWitnetPriceFeed" ); require( __pricefeedId_[address(_pricefeed)] == bytes32(0), "WitnetPriceRouter: already serving a currency pair" ); } bytes memory _caption = abi.encodePacked( "Price-", bytes(_base), "/", bytes(_quote), "-", _decimals.toString() ); bytes32 _erc2362id = keccak256(_caption); Pair storage _record = __pairs[_erc2362id]; address _currentPriceFeed = address(_record.pricefeed); if (bytes(_record.base).length == 0) { _record.base = _base; _record.quote = _quote; _record.decimals = _decimals; __supportedCurrencyPairs.push(_erc2362id); } else if (_currentPriceFeed != address(0)) { __pricefeedId_[_currentPriceFeed] = bytes32(0); } if (address(_pricefeed) != _currentPriceFeed) { __pricefeedId_[address(_pricefeed)] = _erc2362id; } _record.pricefeed = _pricefeed; emit CurrencyPairSet(_erc2362id, _pricefeed); } /// Returns list of known currency pairs IDs. function supportedCurrencyPairs() external view virtual override returns (bytes32[] memory) { return __supportedCurrencyPairs; } /// Returns `true` if given pair is currently being served by a compliant price feed contract. function supportsCurrencyPair(bytes32 _erc2362id) public view virtual override returns (bool) { return address(__pairs[_erc2362id].pricefeed) != address(0); } /// Returns `true` if given price feed contract is currently serving updates to any known currency pair. function supportsPriceFeed(IERC165 _pricefeed) public view virtual override returns (bool) { return __pairs[__pricefeedId_[address(_pricefeed)]].pricefeed == _pricefeed; } } // File: contracts\WitnetPriceFeed.sol // Your contract needs to inherit from UsingWitnet contract WitnetPriceFeed is IWitnetPriceFeed, UsingWitnet, WitnetRequest { using Witnet for bytes; /// Stores the ID of the last price update posted to the Witnet Request Board. uint256 public override latestQueryId; /// Stores the ID of the last price update succesfully solved by the WRB. uint256 internal __lastValidQueryId; /// Constructor. /// @param _witnetRequestBoard WitnetRequestBoard entrypoint address. /// @param _witnetRequestBytecode Raw bytecode of Witnet Data Request to be used on every update request. constructor ( WitnetRequestBoard _witnetRequestBoard, bytes memory _witnetRequestBytecode ) UsingWitnet(_witnetRequestBoard) WitnetRequest(_witnetRequestBytecode) {} /// Estimates minimum fee amount in native currency to be paid when /// requesting a new price update. /// @dev Actual fee depends on the gas price of the `requestUpdate()` transaction. /// @param _gasPrice Gas price expected to be paid when calling `requestUpdate()` function estimateUpdateFee(uint256 _gasPrice) external view virtual override returns (uint256) { return witnet.estimateReward(_gasPrice); } /// Returns result of the last valid price update request successfully solved by the Witnet oracle. function lastPrice() public view virtual override returns (int256 _lastPrice) { Witnet.Result memory _result; uint _latestQueryId = latestQueryId; if ( _latestQueryId > 0 && _witnetCheckResultAvailability(_latestQueryId) ) { _result = witnet.readResponseResult(_latestQueryId); if (_result.success) { return int256(int64(witnet.asUint64(_result))); } } if (__lastValidQueryId > 0) { _result = witnet.readResponseResult(__lastValidQueryId); return int256(int64(witnet.asUint64(_result))); } } /// Returns the EVM-timestamp when last valid price was reported back from the Witnet oracle. function lastTimestamp() public view virtual override returns (uint256 _lastTimestamp) { Witnet.Result memory _result; Witnet.Response memory _response; uint _latestQueryId = latestQueryId; if ( _latestQueryId > 0 && _witnetCheckResultAvailability(_latestQueryId) ) { _response = witnet.readResponse(_latestQueryId); _result = witnet.resultFromCborBytes(_response.cborBytes); if (_result.success) { return _response.timestamp; } } if (__lastValidQueryId > 0) { _response = witnet.readResponse(__lastValidQueryId); return _response.timestamp; } } /// Returns tuple containing last valid price and timestamp, as well as status code of latest update /// request that got posted to the Witnet Request Board. /// @return _lastPrice Last valid price reported back from the Witnet oracle. /// @return _lastTimestamp EVM-timestamp of the last valid price. /// @return _lastDrTxHash Hash of the Witnet Data Request that solved the last valid price. /// @return _latestUpdateStatus Status code of the latest update request. function lastValue() external view virtual override returns ( int _lastPrice, uint _lastTimestamp, bytes32 _lastDrTxHash, uint _latestUpdateStatus ) { uint _latestQueryId = latestQueryId; if (_latestQueryId > 0) { bool _completed = _witnetCheckResultAvailability(_latestQueryId); if (_completed) { Witnet.Response memory _latestResponse = witnet.readResponse(_latestQueryId); Witnet.Result memory _latestResult = witnet.resultFromCborBytes(_latestResponse.cborBytes); if (_latestResult.success) { return ( int256(int64(witnet.asUint64(_latestResult))), _latestResponse.timestamp, _latestResponse.drTxHash, 200 ); } } if (__lastValidQueryId > 0) { Witnet.Response memory _lastValidResponse = witnet.readResponse(__lastValidQueryId); Witnet.Result memory _lastValidResult = witnet.resultFromCborBytes(_lastValidResponse.cborBytes); return ( int256(int64(witnet.asUint64(_lastValidResult))), _lastValidResponse.timestamp, _lastValidResponse.drTxHash, _completed ? 400 : 404 ); } } return (0, 0, 0, 404); } /// Returns identifier of the latest update request posted to the Witnet Request Board. /// @dev Returning 0 while the latest update request remains unsolved. function latestUpdateDrTxHash() external view virtual override returns (bytes32) { uint256 _latestQueryId = latestQueryId; if (_latestQueryId > 0) { if (_witnetCheckResultAvailability(_latestQueryId)) { return witnet.readResponseDrTxHash(_latestQueryId); } } return bytes32(0); } /// Returns error message of latest update request posted to the Witnet Request Board. /// @dev Returning empty string if the latest update request remains unsolved, or /// @dev if it was succesfully solved with no errors. function latestUpdateErrorMessage() external view virtual override returns (string memory _errorMessage) { uint256 _latestQueryId = latestQueryId; if (_latestQueryId > 0) { if (_witnetCheckResultAvailability(_latestQueryId)) { Witnet.Result memory _latestResult = witnet.readResponseResult(_latestQueryId); if (_latestResult.success == false) { (, _errorMessage) = witnet.asErrorMessage(_latestResult); } } } } /// Returns status code of latest update request posted to the Witnet Request Board: /// @dev Status codes: /// @dev - 200: update request was succesfully solved with no errors /// @dev - 400: update request was solved with errors /// @dev - 404: update request was not solved yet function latestUpdateStatus() public view virtual override returns (uint256) { uint _latestQueryId = latestQueryId; if (_latestQueryId > 0) { if (_witnetCheckResultAvailability(_latestQueryId)) { Witnet.Result memory _result = witnet.readResponseResult(_latestQueryId); return ( _result.success ? 200 // OK : 400 // Bad result ); } else { return 404; // not yet solved; } } return 200; } /// Returns `true` if latest update request posted to the Witnet Request Board /// has not been solved yet by the Witnet oracle. function pendingUpdate() public view virtual override returns (bool) { return ( latestQueryId != 0 && !_witnetCheckResultAvailability(latestQueryId) ); } /// Posts a new price update request to the Witnet Request Board. Requires payment of a fee /// that depends on the value of `tx.gasprice`. See `estimateUpdateFee(uint256)`. /// @dev If previous update request was not solved yet, calling this method again allows /// @dev upgrading the update fee if called with a higher `tx.gasprice` value. function requestUpdate() public payable virtual override { uint _usedFunds; uint _latestQueryId = latestQueryId; uint _latestUpdateStatus = latestUpdateStatus(); if (_latestUpdateStatus == 404) { // latest update is still pending, so just raise upgrade reward, // accordingly to current tx gasprice: _usedFunds = _witnetUpgradeReward(_latestQueryId); } else { // Check if latest update ended successfully: if (_latestUpdateStatus == 200) { // If so, remove previous last valid valid query from the WRB: if (__lastValidQueryId > 0) { _witnetDeleteQuery(__lastValidQueryId); } __lastValidQueryId = _latestQueryId; } // Post update request to the WRB: (_latestQueryId, _usedFunds) = _witnetPostRequest(this); // Update latest query id: latestQueryId = _latestQueryId; } // Transfer back unused funds: payable(msg.sender).transfer(msg.value - _usedFunds); if (_usedFunds > 0) { emit PriceFeeding(msg.sender, _latestQueryId, _usedFunds); } } /// Tells whether this contract implements the interface defined by `interfaceId`. /// @dev See the corresponding https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] /// @dev to learn more about how these ids are created. function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) { return ( _interfaceId == type(IERC165).interfaceId || _interfaceId == type(IWitnetPriceFeed).interfaceId ); } }
Returns the EVM-timestamp when last valid price was reported back from the Witnet oracle.
function lastTimestamp() public view virtual override returns (uint256 _lastTimestamp) { Witnet.Result memory _result; Witnet.Response memory _response; uint _latestQueryId = latestQueryId; if ( _latestQueryId > 0 && _witnetCheckResultAvailability(_latestQueryId) ) { _response = witnet.readResponse(_latestQueryId); _result = witnet.resultFromCborBytes(_response.cborBytes); if (_result.success) { return _response.timestamp; } } if (__lastValidQueryId > 0) { _response = witnet.readResponse(__lastValidQueryId); return _response.timestamp; } }
1,303,503
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721) // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ZombieFactory.sol"; /** * the KittyInterface is a external contract and we will excuse the function 'getKitty' * of the constract kittyInterface, this will be defined in another contract */ interface KittyInterface { function getKitty(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ); } contract ZombieFeeding is ZombieFactory { /* * ckAddress is contract address of kittyAddress on ETH blockchain * ref : https://etherscan.io/token/0x06012c8cf97BEaD5deAe237070F9587f8E7A266d * we will create the kittyContract by the address of the kittyInterface */ address ckAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; KittyInterface kittyContract = KittyInterface(ckAddress); /** * ownerOfZombie : modifier to require zombie is own of user who excuse the contract * @param zombieId : id of the zombie need to be checked */ modifier ownerOfZombie(uint zombieId) { //make sure the user excuse this contract same as the mapping zombieToOwer (bool res , address add) = PROTECTED_getAddressByZombieID(zombieId); require(res == true); require(msg.sender == add); _; } /************************************ * EXTERNAL FUNCTION DEFINED HERE * ************************************/ /** * setKittyContractAddress : in case the contract is change, so we re-update the contract of the kitty * attribute 'external' mean that this function can be call outside of the contract * modifier 'onlyOwner()' mean that only owner of contract can use its * @param kittyAdrress : new contract address of the kitty */ function setKittyContractAddress(address kittyAdrress) external onlyOwner() { if(kittyAdrress == ckAddress) { return; } ckAddress = kittyAdrress; kittyContract = KittyInterface(ckAddress); } /********************************** * PUBLIC FUNCTION DEFINED HERE * **********************************/ /** * feedOnKitty : public function that will trigger when zombie eat a kitty * this function will excuse the function from external contract is kittyInterface and return the kittyDna * @param zombieID : id of the zombie * @param kittyID : id of the kitty */ function feedOnKitty(uint zombieID, uint kittyID) public { // get the kittyDna from external contract (,,,,,,,,,uint kittyDna) = kittyContract.getKitty(kittyID); // excuse this .... PROTECTED_feedAndMultiply(zombieID, kittyDna, "kitty"); } /************************************************************************ * PROTECTED FUNCTION DEFINED HERE (IN SOLIDITY DEFINED AS INTERNAL ) * ************************************************************************/ /** * PROTECTED_triggerCooldown : internal function that wil trigger cooldown of the zoombie to begin * @param zombie : the zombie will be triggered */ function PROTECTED_triggerCooldown(Zombie storage zombie) internal { zombie.readyTime = uint32(block.timestamp + cooldownTime); } /** * PROTECTED_isReady : internal function that check the zombie is ready or not * attribute 'view' mean is constant * 'view' also mean that function read on blockchain and dont modify anything on its * @param zombie : the zombie will be checked */ function PROTECTED_isReady(Zombie storage zombie) internal view returns (bool) { return (zombie.readyTime <= block.timestamp); } /** * PROTECTED_feedAndMultiply : protected function that will perform the zombie bite another one and create new zombie * modifier 'ownerOfZombie()' mean that user excute this contract must own the zombie * this function will only permit user that have own the zombie to excuse this * change the 'public' into 'internal' to check the security * @param zombieID : id of the zombie * @param targetDna : DNA of the one is bited */ function PROTECTED_feedAndMultiply(uint zombieID, uint targetDna, string memory species) internal ownerOfZombie(zombieID) { //storage mean the zombie is storage from blockchain network Zombie storage zombie = ls_zombies[zombieID]; //make sure the zombie is ready require(PROTECTED_isReady(zombie) == true); // make sure target dna dont have pass the limit 16 character targetDna = targetDna % dnaDigits; // create new dna by target and zombie dna uint newDna = (targetDna + zombie.dna) / 2; //detect zombie ate kitty or not if (keccak256(abi.encodePacked(species)) == keccak256(abi.encodePacked("kitty"))) { //exp : newDna = 334455 , so newDna of kitty will be 334455 - 334455 % 100 = 334400 + 99 = 334499 newDna = newDna - newDna% 100 + 99; } // create new zombie by new dna PROTECTED_createZombie("Unknown_Name", newDna); //trigger cooldown of the zombie PROTECTED_triggerCooldown(zombie); } }
PROTECTED_isReady : internal function that check the zombie is ready or not attribute 'view' mean is constant 'view' also mean that function read on blockchain and dont modify anything on its zombie : the zombie will be checked/
function PROTECTED_isReady(Zombie storage zombie) internal view returns (bool) { return (zombie.readyTime <= block.timestamp); }
7,304,579
./full_match/42220/0x9d806E9004F21B041fFC941be8D8f4B835369f40/sources/contracts/SOURCE/TokenVesting.sol
Returns the amount of tokens that can be withdrawn by the owner. return the amount of tokens/
function getWithdrawableAmount() public view returns(uint256){ return _token.balanceOf(address(this)) - vestingSchedulesTotalAmount; }
16,334,474
./full_match/1/0x64841AbfA7C33f1d9cBE271F30C8FC0E24e28B2C/sources/src/backend/contracts/FeesHiddenV4/TokenContract.sol
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./ Overflow not possible: amount <= accountBalance <= totalSupply.
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); }
2,912,252
// File contracts/interfaces/IOlympusProFactoryStorage.sol pragma solidity 0.7.5; interface IOlympusProFactoryStorage { function pushBond(address _payoutToken, address _principleToken, address _customTreasury, address _customBond, address _initialOwner, uint[] calldata _tierCeilings, uint[] calldata _fees) external returns(address _treasury, address _bond); } // File contracts/types/Ownable.sol pragma solidity 0.7.5; contract Ownable { address public policy; constructor () { policy = msg.sender; } modifier onlyPolicy() { require( policy == msg.sender, "Ownable: caller is not the owner" ); _; } function transferManagment(address _newOwner) external onlyPolicy() { require( _newOwner != address(0) ); policy = _newOwner; } } // File contracts/libraries/SafeMath.sol pragma solidity 0.7.5; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // File contracts/libraries/Address.sol pragma solidity 0.7.5; library Address { function isContract(address account) internal view returns (bool) { 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 _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); } } } 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 { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } // File contracts/interfaces/IERC20.sol pragma solidity 0.7.5; interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/libraries/SafeERC20.sol pragma solidity 0.7.5; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).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)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/libraries/FullMath.sol pragma solidity 0.7.5; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } // File contracts/libraries/FixedPoint.sol pragma solidity 0.7.5; library Babylonian { function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // File contracts/interfaces/ITreasury.sol pragma solidity 0.7.5; interface ITreasury { function deposit(address _principleTokenAddress, uint _amountPrincipleToken, uint _amountPayoutToken) external; function valueOfToken( address _principleTokenAddress, uint _amount ) external view returns ( uint value_ ); } // File contracts/OlympusProCustomBond.sol pragma solidity 0.7.5; contract CustomBond is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint payout, uint expires ); event BondRedeemed( address recipient, uint payout, uint remaining ); event BondPriceChanged( uint internalPrice, uint debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ IERC20 immutable payoutToken; // token paid for principal IERC20 immutable principalToken; // inflow token ITreasury immutable customTreasury; // pays for and receives principal address immutable olympusDAO; address olympusTreasury; // receives fee uint public totalPrincipalBonded; uint public totalPayoutGiven; Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data FeeTiers[] private feeTiers; // stores fee tiers mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint public lastDecay; // reference block for debt decay address immutable subsidyRouter; // pays subsidy in OHM to custom treasury uint payoutSinceLastSubsidy; // principal accrued since subsidy paid /* ======== STRUCTS ======== */ struct FeeTiers { uint tierCeilings; // principal bonded till next tier uint fees; // in ten-thousandths (i.e. 33300 = 3.33%) } // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principal value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // payout token decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint payout; // payout token remaining to be paid uint vesting; // Blocks left to vest uint lastBlock; // Last interaction uint truePricePaid; // Price paid (principal tokens per payout token) in ten-millionths - 4000000 = 0.4 } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== CONSTRUCTOR ======== */ constructor( address _customTreasury, address _payoutToken, address _principalToken, address _olympusTreasury, address _subsidyRouter, address _initialOwner, address _olympusDAO, uint[] memory _tierCeilings, uint[] memory _fees ) { require( _customTreasury != address(0) ); customTreasury = ITreasury( _customTreasury ); require( _payoutToken != address(0) ); payoutToken = IERC20( _payoutToken ); require( _principalToken != address(0) ); principalToken = IERC20( _principalToken ); require( _olympusTreasury != address(0) ); olympusTreasury = _olympusTreasury; require( _subsidyRouter != address(0) ); subsidyRouter = _subsidyRouter; require( _initialOwner != address(0) ); policy = _initialOwner; require( _olympusDAO != address(0) ); olympusDAO = _olympusDAO; require(_tierCeilings.length == _fees.length, "tier length and fee length not the same"); for(uint i; i < _tierCeilings.length; i++) { feeTiers.push( FeeTiers({ tierCeilings: _tierCeilings[i], fees: _fees[i] })); } } /* ======== INITIALIZATION ======== */ /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBond( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt ) external onlyPolicy() { require( currentDebt() == 0, "Debt must be 0 for initialization" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 10000, "Vesting must be longer than 36 hours" ); terms.vestingTerm = _input; } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyPolicy() { require( _increment <= terms.controlVariable.mul( 30 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice change address of Olympus Treasury * @param _olympusTreasury uint */ function changeOlympusTreasury(address _olympusTreasury) external { require( msg.sender == olympusDAO, "Only Olympus DAO" ); olympusTreasury = _olympusTreasury; } /** * @notice subsidy controller checks payouts since last subsidy and resets counter * @return payoutSinceLastSubsidy_ uint */ function paySubsidy() external returns ( uint payoutSinceLastSubsidy_ ) { require( msg.sender == subsidyRouter, "Only subsidy controller" ); payoutSinceLastSubsidy_ = payoutSinceLastSubsidy; payoutSinceLastSubsidy = 0; } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit(uint _amount, uint _maxPrice, address _depositor) external returns (uint) { require( _depositor != address(0), "Invalid address" ); decayDebt(); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); uint nativePrice = trueBondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = customTreasury.valueOfToken( address(principalToken), _amount ); uint payout = _payoutFor( value ); // payout to bonder is computed require( payout >= 10 ** payoutToken.decimals() / 100, "Bond too small" ); // must be > 0.01 payout token ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( currentOlympusFee() ).div( 1e6 ); /** principal is transferred in approved and deposited into the treasury, returning (_amount - profit) payout token */ principalToken.safeTransferFrom( msg.sender, address(this), _amount ); principalToken.approve( address(customTreasury), _amount ); customTreasury.deposit( address(principalToken), _amount, payout ); if ( fee != 0 ) { // fee is transferred to dao payoutToken.transfer(olympusTreasury, fee); } // total debt is increased totalDebt = totalDebt.add( value ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout.sub(fee) ), vesting: terms.vestingTerm, lastBlock: block.number, truePricePaid: trueBondPrice() }); // indexed events are emitted emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ) ); emit BondPriceChanged( _bondPrice(), debtRatio() ); totalPrincipalBonded = totalPrincipalBonded.add(_amount); // total bonded increased totalPayoutGiven = totalPayoutGiven.add(payout); // total payout increased payoutSinceLastSubsidy = payoutSinceLastSubsidy.add( payout ); // subsidy counter increased adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @return uint */ function redeem(address _depositor) external returns (uint) { Bond memory info = bondInfo[ _depositor ]; uint percentVested = percentVestedFor( _depositor ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _depositor ]; // delete user info emit BondRedeemed( _depositor, info.payout, 0 ); // emit bond data payoutToken.transfer( _depositor, info.payout ); return info.payout; } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _depositor ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, truePricePaid: info.truePricePaid }); emit BondRedeemed( _depositor, payout, bondInfo[ _depositor ].payout ); payoutToken.transfer( _depositor, payout ); return payout; } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer ); if( adjustment.rate != 0 && block.number >= blockCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = block.number; } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /* ======== VIEW FUNCTIONS ======== */ /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate true bond price a user pays * @return price_ uint */ function trueBondPrice() public view returns ( uint price_ ) { price_ = bondPrice().add(bondPrice().mul( currentOlympusFee() ).div( 1e6 ) ); } /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return payoutToken.totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate total interest due for new bond * @param _value uint * @return uint */ function _payoutFor( uint _value ) internal view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 ); } /** * @notice calculate user's interest due for new bond, accounting for Olympus Fee * @param _value uint * @return uint */ function payoutFor( uint _value ) external view returns ( uint ) { uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 ); return total.sub(total.mul( currentOlympusFee() ).div( 1e6 )); } /** * @notice calculate current ratio of debt to payout token supply * @notice protocols using Olympus Pro should be careful when quickly adding large %s to total supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { debtRatio_ = FixedPoint.fraction( currentDebt().mul( 10 ** payoutToken.decimals() ), payoutToken.totalSupply() ).decode112with18().div( 1e18 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint blocksSinceLast = block.number.sub( lastDecay ); decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of payout token available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /** * @notice current fee Olympus takes of each bond * @return currentFee_ uint */ function currentOlympusFee() public view returns( uint currentFee_ ) { uint tierLength = feeTiers.length; for(uint i; i < tierLength; i++) { if(totalPrincipalBonded < feeTiers[i].tierCeilings || i == tierLength - 1 ) { return feeTiers[i].fees; } } } } // File contracts/OlympusProCustomTreasury.sol pragma solidity 0.7.5; contract CustomTreasury is Ownable { /* ======== DEPENDENCIES ======== */ using SafeERC20 for IERC20; using SafeMath for uint; /* ======== STATE VARIABLS ======== */ address public immutable payoutToken; mapping(address => bool) public bondContract; /* ======== EVENTS ======== */ event BondContractToggled(address bondContract, bool approved); event Withdraw(address token, address destination, uint amount); /* ======== CONSTRUCTOR ======== */ constructor(address _payoutToken, address _initialOwner) { require( _payoutToken != address(0) ); payoutToken = _payoutToken; require( _initialOwner != address(0) ); policy = _initialOwner; } /* ======== BOND CONTRACT FUNCTION ======== */ /** * @notice deposit principle token and recieve back payout token * @param _principleTokenAddress address * @param _amountPrincipleToken uint * @param _amountPayoutToken uint */ function deposit(address _principleTokenAddress, uint _amountPrincipleToken, uint _amountPayoutToken) external { require(bondContract[msg.sender], "msg.sender is not a bond contract"); IERC20(_principleTokenAddress).safeTransferFrom(msg.sender, address(this), _amountPrincipleToken); IERC20(payoutToken).safeTransfer(msg.sender, _amountPayoutToken); } /* ======== VIEW FUNCTION ======== */ /** * @notice returns payout token valuation of priciple * @param _principleTokenAddress address * @param _amount uint * @return value_ uint */ function valueOfToken( address _principleTokenAddress, uint _amount ) public view returns ( uint value_ ) { // convert amount to match payout token decimals value_ = _amount.mul( 10 ** IERC20( payoutToken ).decimals() ).div( 10 ** IERC20( _principleTokenAddress ).decimals() ); } /* ======== POLICY FUNCTIONS ======== */ /** * @notice policy can withdraw ERC20 token to desired address * @param _token uint * @param _destination address * @param _amount uint */ function withdraw(address _token, address _destination, uint _amount) external onlyPolicy() { IERC20(_token).safeTransfer(_destination, _amount); emit Withdraw(_token, _destination, _amount); } /** @notice toggle bond contract @param _bondContract address */ function toggleBondContract(address _bondContract) external onlyPolicy() { bondContract[_bondContract] = !bondContract[_bondContract]; emit BondContractToggled(_bondContract, bondContract[_bondContract]); } } // File contracts/OlympusProFactory.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; contract OlympusProFactory is Ownable { /* ======== STATE VARIABLS ======== */ address immutable public olympusTreasury; address immutable public olympusProFactoryStorage; address immutable public olumpusProSubsidyRouter; address immutable public olympusDAO; /* ======== CONSTRUCTION ======== */ constructor(address _olympusTreasury, address _olympusProFactoryStorage, address _olumpusProSubsidyRouter, address _olympusDAO) { require( _olympusTreasury != address(0) ); olympusTreasury = _olympusTreasury; require( _olympusProFactoryStorage != address(0) ); olympusProFactoryStorage = _olympusProFactoryStorage; require( _olumpusProSubsidyRouter != address(0) ); olumpusProSubsidyRouter = _olumpusProSubsidyRouter; require( _olympusDAO != address(0) ); olympusDAO = _olympusDAO; } /* ======== POLICY FUNCTIONS ======== */ /** @notice deploys custom treasury and custom bond contracts and returns address of both @param _payoutToken address @param _principleToken address @param _initialOwner address @return _treasury address @return _bond address */ function createBondAndTreasury(address _payoutToken, address _principleToken, address _initialOwner, uint[] calldata _tierCeilings, uint[] calldata _fees) external onlyPolicy() returns(address _treasury, address _bond) { CustomTreasury treasury = new CustomTreasury(_payoutToken, _initialOwner); CustomBond bond = new CustomBond(address(treasury), _payoutToken, _principleToken, olympusTreasury, olumpusProSubsidyRouter, _initialOwner, olympusDAO, _tierCeilings, _fees); return IOlympusProFactoryStorage(olympusProFactoryStorage).pushBond( _payoutToken, _principleToken, address(treasury), address(bond), _initialOwner, _tierCeilings, _fees ); } /** @notice deploys custom treasury and custom bond contracts and returns address of both @param _payoutToken address @param _principleToken address @param _customTreasury address @param _initialOwner address @return _treasury address @return _bond address */ function createBond(address _payoutToken, address _principleToken, address _customTreasury, address _initialOwner, uint[] calldata _tierCeilings, uint[] calldata _fees ) external onlyPolicy() returns(address _treasury, address _bond) { CustomBond bond = new CustomBond(_customTreasury, _payoutToken, _principleToken, _customTreasury, olumpusProSubsidyRouter, _initialOwner, olympusDAO, _tierCeilings, _fees); return IOlympusProFactoryStorage(olympusProFactoryStorage).pushBond( _payoutToken, _principleToken, _customTreasury, address(bond), _initialOwner, _tierCeilings, _fees ); } }
calculate total interest due for new bond _value uint return uint/
function _payoutFor( uint _value ) internal view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 ); }
333,599
./full_match/1/0x0bC24E61DAAd6293A1b3b53a7D01086BfF0Ea6e5/sources/contracts/WiseSecurity/WiseSecurityHelper.sol
Check if the postion with {_nftId} is locked for interactions./
function _checkPositionLocked( uint256 _nftId ) internal view { if (WISE_LENDING.positionLocked(_nftId) == true) { revert PositionLocked(); } }
4,818,535
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "../../@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../../@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "../../@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../../@openzeppelin/contracts/access/Ownable.sol"; contract ERC721NFTStakingBasicDrip is IERC721Receiver, Ownable { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.Bytes32Set; event Stake(address indexed owner, address indexed nftContract, uint256 indexed tokenId, address rewardToken); event UnStake(address indexed owner, address indexed nftContract, uint256 indexed tokenId, address rewardToken); event RewardWalletChanged(address indexed oldRewardWallet, address indexed newRewardWallet); event MinimumStakingTimeChanged(uint256 indexed oldTime, uint256 newTime); event PermittedRewardToken(address indexed token, uint256 dripRate); event ChangeDripRate(address indexed token, uint256 oldDripRate, uint256 newDripRate); event DeniedRewardToken(address indexed token, uint256 dripRate); event PermittedNFTContract(address indexed nftContract); event DeniedNFTContract(address indexed nftContract); event ClaimRewards(bytes32 indexed stakeId, address indexed owner, uint256 indexed amount); event ReceivedERC721(address operator, address from, uint256 tokenId, bytes data, uint256 gas); // holds the list of permitted NFTs EnumerableSet.AddressSet private permittedNFTs; // holds the list of currently permitted reward tokens EnumerableSet.AddressSet private permittedRewardTokens; // holds the list of all permitted reward tokens (active or not) EnumerableSet.AddressSet private allRewardTokens; // holds the reward token drip rate mapping(address => uint256) public rewardTokenDripRate; struct StakedNFT { bytes32 stakeId; // the stake id of the stake address owner; // the owner of the NFT IERC721 nftContract; // the ERC721 contract for which the NFT belongs uint256 tokenId; // the token ID staked uint256 stakedTimestamp; // the time that the NFT was staked uint256 lastClaimTimestamp; // the last time that the user claimed rewards for this NFT IERC20 rewardToken; // the token to reward for staking } struct ClaimableInfo { bytes32 stakeId; // the stake id address rewardToken; // the token to reward for staking uint256 amount; // the amount of the reward for the stake id } // holds the mapping of stake ids to the staked NFT values mapping(bytes32 => StakedNFT) public stakedNFTs; // holds the mapping of stakers to their staking ids mapping(address => EnumerableSet.Bytes32Set) private userStakes; // holds the mapping of the staker's reward payments mapping(address => mapping(address => uint256)) private userRewards; // holds the number of staked NFTs per reward token mapping(address => uint256) public stakesPerRewardToken; // holds the amount of rewards paid by reward token for all users mapping(address => uint256) public rewardsPaid; // holds the address of the wallet that contains the staking rewards address public rewardWallet; // the minimum amount of time required before claiming rewards via the drip uint256 public MINIMUM_STAKING_TIME_FOR_REWARDS; constructor(address _rewardWallet) { // if we specify a null address for the reward wallet, then we'll use ourself rewardWallet = (_rewardWallet != address(0)) ? _rewardWallet : address(this); MINIMUM_STAKING_TIME_FOR_REWARDS = 24 hours; emit RewardWalletChanged(address(0), _rewardWallet); emit MinimumStakingTimeChanged(0, MINIMUM_STAKING_TIME_FOR_REWARDS); } /****** STANDARD OPERATIONS ******/ /** * @dev returns information regarding how long the current rewards for the token * in the reward wallet can maintain the current drip rate */ function runway(IERC20 token) public view returns ( uint256 _balance, uint256 _dripRatePerSecond, uint256 _stakeCount, uint256 _runRatePerSecond, uint256 _runRatePerDay, uint256 _runwaySeconds, uint256 _runwayDays ) { _balance = token.balanceOf(rewardWallet); _stakeCount = stakesPerRewardToken[address(token)]; _dripRatePerSecond = rewardTokenDripRate[address(token)]; _runRatePerSecond = _dripRatePerSecond * _stakeCount; _runRatePerDay = _runRatePerSecond * 24 hours; if (_runRatePerSecond != 0) { _runwaySeconds = _balance / _runRatePerSecond; } else { _runwaySeconds = type(uint256).max; } _runwayDays = _runwaySeconds / 24 hours; } /** * @dev returns an array of all staked NFT for the specified account */ function staked(address account) public view returns (StakedNFT[] memory) { // retrieve all of the stake ids for the caller bytes32[] memory ids = stakeIds(account); // construct the temporary staked information StakedNFT[] memory stakes = new StakedNFT[](ids.length); for (uint256 i = 0; i < ids.length; i++) { stakes[i] = stakedNFTs[ids[i]]; } return stakes; } /** * @dev returns a paired set of arrays that gives the history of * all rewards paid to account regardless of if the contract * currently permits the reward token */ function rewardHistory(address account) public view returns (address[] memory _rewardTokens, uint256[] memory _rewardsPaid) { _rewardTokens = allRewardTokens.values(); _rewardsPaid = new uint256[](allRewardTokens.length()); for (uint256 i = 0; i < _rewardTokens.length; i++) { _rewardsPaid[i] = userRewards[account][_rewardTokens[i]]; } } /** * @dev retrieves the stake ids for the specified account */ function stakeIds(address account) public view returns (bytes32[] memory) { return userStakes[account].values(); } /** * @dev changes the reward wallet */ function setRewardWallet(address wallet) public onlyOwner { address old = rewardWallet; // if we specify a null address for the reward wallet, then we'll use ourself rewardWallet = (wallet != address(0)) ? wallet : address(this); emit RewardWalletChanged(old, rewardWallet); } /** * @dev updates the minimum staking time for rewards */ function setMinimumStakingTimeForRewards(uint256 minimumStakingTime) public onlyOwner { require(minimumStakingTime >= 900, "must be at least 900 seconds due to block timestamp variations"); uint256 old = MINIMUM_STAKING_TIME_FOR_REWARDS; MINIMUM_STAKING_TIME_FOR_REWARDS = minimumStakingTime; emit MinimumStakingTimeChanged(old, minimumStakingTime); } /** * @dev sends the amount of the token specified from the contract to the caller */ function withdraw(IERC20 token, uint256 amount) public onlyOwner { token.safeTransfer(_msgSender(), amount); } /****** STAKING REWARD CLAIMING METHODS ******/ /** * @dev calculates the claimable balance for the given stake ID */ function _claimableBalance(bytes32 stakeId) internal view returns (uint256) { StakedNFT memory info = stakedNFTs[stakeId]; // if they haven't staked long enough, their claimable rewards are 0 if (block.timestamp < info.stakedTimestamp + MINIMUM_STAKING_TIME_FOR_REWARDS) { return 0; } // calculate how long it's been since the last time they claimed uint256 delta = block.timestamp - info.lastClaimTimestamp; // calculate how much is claimable based upon the drip rate for the token * the time elapsed return rewardTokenDripRate[address(info.rewardToken)] * delta; } /** * @dev returns all of the claimable stakes for the specified account */ function claimable(address account) public view returns (ClaimableInfo[] memory) { // retrieve all of the stake ids for the caller bytes32[] memory ids = stakeIds(account); // construct the temporary claimable information ClaimableInfo[] memory claims = new ClaimableInfo[](ids.length); // loop through all of the caller's stake ids for (uint256 i = 0; i < ids.length; i++) { // construct the claimable information structure claims[i] = ClaimableInfo({ stakeId: ids[i], rewardToken: address(stakedNFTs[ids[i]].rewardToken), amount: _claimableBalance(ids[i]) }); } return claims; } /** * @dev claims the stake with the given ID * * Requirements: * * - Must be owner of the stake id */ function claim(bytes32 stakeId) public { _claim(stakeId); } /** * @dev claims all of the available stakes for the specified account */ function claimAll(address account) public { // retrieve all of the stake ids for the caller bytes32[] memory ids = stakeIds(account); // loop through all of the caller's stake ids for (uint256 i = 0; i < ids.length; i++) { _claim(ids[i]); // process the claim } } /** * @dev internal method called when claiming staking rewards */ function _claim(bytes32 stakeId) internal { StakedNFT memory info = stakedNFTs[stakeId]; // get the claimable balance for this stake id uint256 _claimableAmount = _claimableBalance(stakeId); // if they have nothing to claim, return early (saves gas) if (_claimableAmount == 0) { return; } // if we are to pull funds from a reward wallet and it doesn't have permission // to use those funds then let's go ahead and return if ( rewardWallet != address(this) && info.rewardToken.allowance(rewardWallet, address(this)) < _claimableAmount ) { return; } // update the last claimed timestamp stakedNFTs[stakeId].lastClaimTimestamp = block.timestamp; // add the reward amount to the total amount for the reward token that we have paid out rewardsPaid[address(info.rewardToken)] += _claimableAmount; // add the reward amount to the users individual tracking of what we've paid out userRewards[info.owner][address(info.rewardToken)] += _claimableAmount; if (rewardWallet != address(this)) { // transfer the claimable rewards to the owner from the reward wallet info.rewardToken.safeTransferFrom(rewardWallet, info.owner, _claimableAmount); } else { // else, transfer the rewards to the owner from the balance // of the token held by the contract info.rewardToken.safeTransfer(info.owner, _claimableAmount); } emit ClaimRewards(stakeId, info.owner, _claimableAmount); } /****** STAKING METHODS ******/ function _generateStakeId( address owner, address nftContract, uint256 tokenId ) internal view returns (bytes32) { return keccak256(abi.encodePacked(owner, nftContract, tokenId, block.timestamp, block.number)); } /** * @dev allows a user to stake their NFT into the contract * * Requirements: * * - contract must be approved for all NFTs of the owner in the NFT contract */ function stake( IERC721 nftContract, uint256 tokenId, IERC20 rewardToken ) public returns (bytes32) { require(permittedNFTs.contains(address(nftContract)), "NFT is not permitted to be staked"); require(permittedRewardTokens.contains(address(rewardToken)), "Reward token is not permitted"); require( nftContract.isApprovedForAll(_msgSender(), address(this)) || nftContract.getApproved(tokenId) == address(this), "not permitted to take ownership of NFT for staking" ); // take ownership of the NFT nftContract.safeTransferFrom(_msgSender(), address(this), tokenId); // generate the stake ID bytes32 stakeId = _generateStakeId(_msgSender(), address(nftContract), tokenId); // add the stake Id record stakedNFTs[stakeId] = StakedNFT({ stakeId: stakeId, owner: _msgSender(), nftContract: nftContract, tokenId: tokenId, stakedTimestamp: block.timestamp, lastClaimTimestamp: block.timestamp, rewardToken: rewardToken }); // add the stake ID to the user's tracking userStakes[_msgSender()].add(stakeId); // increment the number of stakes for the given reward token stakesPerRewardToken[address(rewardToken)] += 1; emit Stake(_msgSender(), address(nftContract), tokenId, address(rewardToken)); return stakeId; } /** * @dev allows the user to unstake their NFT using the specified stake ID */ function unstake(bytes32 stakeId) public { require(stakedNFTs[stakeId].owner == _msgSender(), "not the owner of the specified stake id"); // this also implicitly requires that the stake id exists // pull the staked NFT info StakedNFT memory info = stakedNFTs[stakeId]; // claim before unstake _claim(stakeId); // delete the record delete stakedNFTs[stakeId]; // delete the stake ID from the user's tracking userStakes[info.owner].remove(stakeId); // decrement the number of stakes for the given reward token stakesPerRewardToken[address(info.rewardToken)] -= 1; // transfer the NFT back to the user info.nftContract.safeTransferFrom(address(this), info.owner, info.tokenId); emit UnStake(info.owner, address(info.nftContract), info.tokenId, address(info.rewardToken)); } /****** MANAGEMENT OF PERMITTED REWARD TOKENS ******/ function isPermittedRewardToken(address token) public view returns (bool) { return permittedRewardTokens.contains(token); } /** * @dev returns an array of the permitted reward tokens */ function rewardTokens() public view returns (address[] memory) { return permittedRewardTokens.values(); } /** * @dev adds the specified token as a permitted reward token at the specified drip rate * * WARNING: amountOfTokenPerDayPerNFT is expressed as the amount of the token to * drip per day per NFT expressed in atomic units (gwei) * ex. FTM has 18 decimals; therefore, * 1.0 FTM = 1000000000000000000 atomic units * a dripRate of 1 would drip 0.000000000000000001 a second per NFT * */ function permitRewardToken(address token, uint256 amountOfTokenPerDayPerNFT) public onlyOwner { require(!permittedRewardTokens.contains(token), "Reward token is already permitted"); permittedRewardTokens.add(token); // keeps track of all tokens that have been permitted in the past // so that we can track all payouts for all rewards tokens for users // as such, we only want to add it to the set once in case it is added // again later after it has been removed if (!allRewardTokens.contains(token)) { allRewardTokens.add(token); } // set the drip rate based upon the amount released per day divided by the seconds in a day rewardTokenDripRate[token] = amountOfTokenPerDayPerNFT / 24 hours; require(rewardTokenDripRate[token] != 0, "amountOfTokenPerDayPerNFT results in a zero (0) drip rate"); emit PermittedRewardToken(token, rewardTokenDripRate[token]); } /** * @dev updates the drip rate for the given token to the specified value * * WARNING: amountOfTokenPerDayPerNFT is expressed as the amount of the token to * drip per day per NFT expressed in atomic units (gwei) * ex. FTM has 18 decimals; therefore, * 1.0 FTM = 1000000000000000000 atomic units * a dripRate of 1 would drip 0.000000000000000001 a second per NFT * */ function setRewardTokenDripRate(address token, uint256 amountOfTokenPerDayPerNFT) public onlyOwner { require(permittedRewardTokens.contains(token), "Reward token is not permitted"); uint256 old = rewardTokenDripRate[token]; // set the drip rate based upon the amount released per day divided by the seconds in a day rewardTokenDripRate[token] = amountOfTokenPerDayPerNFT / 24 hours; require(rewardTokenDripRate[token] != 0, "amountOfTokenPerDayPerNFT results in a zero (0) drip rate"); emit ChangeDripRate(token, old, rewardTokenDripRate[token]); } /** * @dev removes the specified token from the permitted reward token list * * WARNING: If a user still has a staked NFT for the reward token * their selected reward token will not switch to something * else and they will still be able to claim the drip rewards * assuming that the reward wallet has enough of a balance of * the token to do pay it out. This method simply stops letting * users select the reward token as the reward for staking their NFT * * Requirements: * * - Token must not be currently used by a staked user */ function denyRewardToken(address token) public onlyOwner { require(permittedRewardTokens.contains(token), "Reward token is not permitted"); uint256 dripRate = rewardTokenDripRate[token]; permittedRewardTokens.remove(token); emit DeniedRewardToken(token, dripRate); } /****** MANAGEMENT OF PERMITTED NFTs ******/ function isPermittedNFT(address nftContract) public view returns (bool) { return permittedNFTs.contains(nftContract); } /** * @dev returns an array of the permitted NFTs */ function nfts() public view returns (address[] memory) { return permittedNFTs.values(); } /** * @dev adds the specified nft contract as an acceptable NFT for staking purposes */ function permitNFT(address nftContract) public onlyOwner { require(!permittedNFTs.contains(nftContract), "NFT already permitted"); permittedNFTs.add(nftContract); emit PermittedNFTContract(nftContract); } /** * @dev removes the specified nft contract from being an acceptable NFT for staking purposes */ function denyNFT(address nftContract) public onlyOwner { require(permittedNFTs.contains(nftContract), "NFT is not permitted"); permittedNFTs.remove(nftContract); emit DeniedNFTContract(nftContract); } /** * @dev handles IERC721.safeTransferFrom() */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) public override returns (bytes4) { require(operator == address(this), "Cannot send tokens to contract directly"); emit ReceivedERC721(operator, from, tokenId, data, gasleft()); return IERC721Receiver.onERC721Received.selector; } }
allows the user to unstake their NFT using the specified stake ID/ pull the staked NFT info claim before unstake delete the record delete the stake ID from the user's tracking decrement the number of stakes for the given reward token transfer the NFT back to the user
function unstake(bytes32 stakeId) public { StakedNFT memory info = stakedNFTs[stakeId]; _claim(stakeId); delete stakedNFTs[stakeId]; userStakes[info.owner].remove(stakeId); stakesPerRewardToken[address(info.rewardToken)] -= 1; info.nftContract.safeTransferFrom(address(this), info.owner, info.tokenId); emit UnStake(info.owner, address(info.nftContract), info.tokenId, address(info.rewardToken)); }
7,277,953
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./FixedPoint.sol"; library Position { using FixedPoint for uint256; uint256 internal constant ONE = 1e18; uint256 internal constant RATIO_PRECISION_SHIFT = 1e4; // RATIO_PRECISION = 1e14 struct Info { uint96 notional; // initial notional = collateral * leverage uint96 debt; // debt uint48 entryToMidRatio; // ratio of entryPrice / _midFromFeed() at build bool isLong; // whether long or short bool liquidated; // whether has been liquidated uint256 oiShares; // shares of aggregate open interest on side } /*/////////////////////////////////////////////////////////////// POSITIONS MAPPING FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Retrieves a position from positions mapping function get( mapping(bytes32 => Info) storage self, address owner, uint256 id ) internal view returns (Info storage position_) { position_ = self[keccak256(abi.encodePacked(owner, id))]; } /// @notice Stores a position in positions mapping function set( mapping(bytes32 => Info) storage self, address owner, uint256 id, Info memory position ) internal { self[keccak256(abi.encodePacked(owner, id))] = position; } /*/////////////////////////////////////////////////////////////// POSITION CAST GETTER FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Computes the position's initial notional cast to uint256 function _notional(Info memory self) private pure returns (uint256) { return uint256(self.notional); } /// @notice Computes the position's initial open interest cast to uint256 function _oiShares(Info memory self) private pure returns (uint256) { return uint256(self.oiShares); } /// @notice Computes the position's debt cast to uint256 function _debt(Info memory self) private pure returns (uint256) { return uint256(self.debt); } /// @notice Whether the position exists /// @dev Is false if position has been liquidated or has zero oi function exists(Info memory self) internal pure returns (bool exists_) { return (!self.liquidated && self.notional > 0); } /*/////////////////////////////////////////////////////////////// POSITION ENTRY PRICE FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Computes the entryToMidRatio cast to uint48 to be set /// @notice on position build function calcEntryToMidRatio(uint256 _entryPrice, uint256 _midPrice) internal pure returns (uint48) { require(_entryPrice <= 2 * _midPrice, "OVLV1: value == 0 at entry"); return uint48(_entryPrice.divDown(_midPrice) / RATIO_PRECISION_SHIFT); } /// @notice Computes the ratio of the entryPrice of position to the midPrice /// @notice at build cast to uint256 function getEntryToMidRatio(Info memory self) internal pure returns (uint256) { return (uint256(self.entryToMidRatio) * RATIO_PRECISION_SHIFT); } /// @notice Computes the entryPrice of the position cast to uint256 /// @dev entryPrice = entryToMidRatio * midPrice (at build) function entryPrice(Info memory self) internal pure returns (uint256 entryPrice_) { uint256 priceRatio = getEntryToMidRatio(self); uint256 oi = _oiShares(self); uint256 q = _notional(self); // will only be zero if all oi shares unwound; handles 0/0 case // of notion / oi if (oi == 0) { return 0; } // entry = ratio * mid = ratio * (notional / oi) entryPrice_ = priceRatio.mulUp(q).divUp(oi); } /*/////////////////////////////////////////////////////////////// POSITION FRACTIONAL GETTER FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Computes the initial notional of position when built /// @dev use mulUp to avoid rounding leftovers on unwind function notionalInitial(Info memory self, uint256 fraction) internal pure returns (uint256) { return _notional(self).mulUp(fraction); } /// @notice Computes the initial open interest of position when built /// @dev use mulUp to avoid rounding leftovers on unwind function oiInitial(Info memory self, uint256 fraction) internal pure returns (uint256) { return _oiShares(self).mulUp(fraction); } /// @notice Computes the current shares of open interest position holds /// @notice on pos.isLong side of the market /// @dev use mulUp to avoid rounding leftovers on unwind function oiSharesCurrent(Info memory self, uint256 fraction) internal pure returns (uint256) { return _oiShares(self).mulUp(fraction); } /// @notice Computes the current debt position holds /// @dev use mulUp to avoid rounding leftovers on unwind function debtCurrent(Info memory self, uint256 fraction) internal pure returns (uint256) { return _debt(self).mulUp(fraction); } /// @notice Computes the current open interest of a position accounting for /// @notice potential funding payments between long/short sides /// @dev returns zero when oiShares = oiTotalOnSide = oiTotalSharesOnSide = 0 to avoid /// @dev div by zero errors /// @dev use mulUp, divUp to avoid rounding leftovers on unwind function oiCurrent( Info memory self, uint256 fraction, uint256 oiTotalOnSide, uint256 oiTotalSharesOnSide ) internal pure returns (uint256) { uint256 posOiShares = oiSharesCurrent(self, fraction); if (posOiShares == 0 || oiTotalOnSide == 0) return 0; return posOiShares.mulUp(oiTotalOnSide).divUp(oiTotalSharesOnSide); } /*/////////////////////////////////////////////////////////////// POSITION CALC FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Computes the position's cost cast to uint256 /// WARNING: be careful modifying notional and debt on unwind function cost(Info memory self, uint256 fraction) internal pure returns (uint256) { uint256 posNotionalInitial = notionalInitial(self, fraction); uint256 posDebt = debtCurrent(self, fraction); // should always be > 0 but use subFloor to be safe w reverts uint256 posCost = posNotionalInitial; posCost = posCost.subFloor(posDebt); return posCost; } /// @notice Computes the value of a position /// @dev Floors to zero, so won't properly compute if self is underwater function value( Info memory self, uint256 fraction, uint256 oiTotalOnSide, uint256 oiTotalSharesOnSide, uint256 currentPrice, uint256 capPayoff ) internal pure returns (uint256 val_) { uint256 posOiInitial = oiInitial(self, fraction); uint256 posNotionalInitial = notionalInitial(self, fraction); uint256 posDebt = debtCurrent(self, fraction); uint256 posOiCurrent = oiCurrent(self, fraction, oiTotalOnSide, oiTotalSharesOnSide); uint256 posEntryPrice = entryPrice(self); // NOTE: PnL = +/- oiCurrent * [currentPrice - entryPrice]; ... (w/o capPayoff) // NOTE: fundingPayments = notionalInitial * ( oiCurrent / oiInitial - 1 ) // NOTE: value = collateralInitial + PnL + fundingPayments // NOTE: = notionalInitial - debt + PnL + fundingPayments if (self.isLong) { // val = notionalInitial * oiCurrent / oiInitial // + oiCurrent * min[currentPrice, entryPrice * (1 + capPayoff)] // - oiCurrent * entryPrice - debt val_ = posNotionalInitial.mulUp(posOiCurrent).divUp(posOiInitial) + Math.min( posOiCurrent.mulUp(currentPrice), posOiCurrent.mulUp(posEntryPrice).mulUp(ONE + capPayoff) ); // floor to 0 val_ = val_.subFloor(posDebt + posOiCurrent.mulUp(posEntryPrice)); } else { // NOTE: capPayoff >= 1, so no need to include w short // val = notionalInitial * oiCurrent / oiInitial + oiCurrent * entryPrice // - oiCurrent * currentPrice - debt val_ = posNotionalInitial.mulUp(posOiCurrent).divUp(posOiInitial) + posOiCurrent.mulUp(posEntryPrice); // floor to 0 val_ = val_.subFloor(posDebt + posOiCurrent.mulUp(currentPrice)); } } /// @notice Computes the current notional of a position including PnL /// @dev Floors to debt if value <= 0 function notionalWithPnl( Info memory self, uint256 fraction, uint256 oiTotalOnSide, uint256 oiTotalSharesOnSide, uint256 currentPrice, uint256 capPayoff ) internal pure returns (uint256 notionalWithPnl_) { uint256 posValue = value( self, fraction, oiTotalOnSide, oiTotalSharesOnSide, currentPrice, capPayoff ); uint256 posDebt = debtCurrent(self, fraction); notionalWithPnl_ = posValue + posDebt; } /// @notice Computes the trading fees to be imposed on a position for build/unwind function tradingFee( Info memory self, uint256 fraction, uint256 oiTotalOnSide, uint256 oiTotalSharesOnSide, uint256 currentPrice, uint256 capPayoff, uint256 tradingFeeRate ) internal pure returns (uint256 tradingFee_) { uint256 posNotional = notionalWithPnl( self, fraction, oiTotalOnSide, oiTotalSharesOnSide, currentPrice, capPayoff ); tradingFee_ = posNotional.mulUp(tradingFeeRate); } /// @notice Whether a position can be liquidated /// @dev is true when value * (1 - liq fee rate) < maintenance margin /// @dev liq fees are reward given to liquidator function liquidatable( Info memory self, uint256 oiTotalOnSide, uint256 oiTotalSharesOnSide, uint256 currentPrice, uint256 capPayoff, uint256 maintenanceMarginFraction, uint256 liquidationFeeRate ) internal pure returns (bool can_) { uint256 fraction = ONE; uint256 posNotionalInitial = notionalInitial(self, fraction); if (self.liquidated || posNotionalInitial == 0) { // already been liquidated return false; } uint256 val = value( self, fraction, oiTotalOnSide, oiTotalSharesOnSide, currentPrice, capPayoff ); uint256 maintenanceMargin = posNotionalInitial.mulUp(maintenanceMarginFraction); uint256 liquidationFee = val.mulDown(liquidationFeeRate); can_ = val < maintenanceMargin + liquidationFee; } }
Computes the current open interest of a position accounting for potential funding payments between long/short sides returns zero when oiShares = oiTotalOnSide = oiTotalSharesOnSide = 0 to avoid div by zero errors use mulUp, divUp to avoid rounding leftovers on unwind
function oiCurrent( Info memory self, uint256 fraction, uint256 oiTotalOnSide, uint256 oiTotalSharesOnSide ) internal pure returns (uint256) { uint256 posOiShares = oiSharesCurrent(self, fraction); if (posOiShares == 0 || oiTotalOnSide == 0) return 0; return posOiShares.mulUp(oiTotalOnSide).divUp(oiTotalSharesOnSide); } POSITION CALC FUNCTIONS
15,830,185
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompoundMonitorProxy.sol"; import "./CompoundSubscriptions.sol"; import "../../interfaces/GasTokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/AutomaticLogger.sol"; import "../CompoundLoanInfo.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract CompoundMonitor is AdminAuth, DSMath, CompoundLoanInfo { enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 30; uint public BOOST_GAS_TOKEN = 19; uint constant public MAX_GAS_PRICE = 80000000000; // 80 gwei uint public REPAY_GAS_COST = 2200000; uint public BOOST_GAS_COST = 1500000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant AUTOMATIC_LOGGER_ADDRESS = 0xAD32Ce09DE65971fFA8356d7eF0B783B82Fd1a9A; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; GasTokenInterface gasToken = GasTokenInterface(GAS_TOKEN_INTERFACE_ADDRESS); address public compoundFlashLoanTakerAddress; AutomaticLogger public logger = AutomaticLogger(AUTOMATIC_LOGGER_ADDRESS); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { approvedCallers[msg.sender] = true; compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _data Amount and exchange data [amount, minPrice, exchangeType, gasCost, 0xPrice] /// @param _addrData cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _callData 0x callData /// @param _user The actual address that owns the Compound position function repayFor( uint[5] memory _data, // amount, minPrice, exchangeType, gasCost, 0xPrice address[3] memory _addrData, // cCollAddress, cBorrowAddress, exchangeAddress bytes memory _callData, address _user ) public payable onlyApproved { if (gasToken.balanceOf(address(this)) >= BOOST_GAS_TOKEN) { gasToken.free(BOOST_GAS_TOKEN); } (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint gasCost = calcGasCost(REPAY_GAS_COST); _data[4] = gasCost; compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature("repayWithLoan(uint256[5],address[3],bytes)", _data, _addrData, _callData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.logRepay(0, msg.sender, _data[0], ratioBefore, ratioAfter); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _data Amount and exchange data [amount, minPrice, exchangeType, gasCost, 0xPrice] /// @param _addrData cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _callData 0x callData /// @param _user The actual address that owns the Compound position function boostFor( uint[5] memory _data, // amount, minPrice, exchangeType, gasCost, 0xPrice address[3] memory _addrData, // cCollAddress, cBorrowAddress, exchangeAddress bytes memory _callData, address _user ) public payable onlyApproved { if (gasToken.balanceOf(address(this)) >= REPAY_GAS_TOKEN) { gasToken.free(REPAY_GAS_TOKEN); } (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint gasCost = calcGasCost(BOOST_GAS_COST); _data[4] = gasCost; compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature("boostWithLoan(uint256[5],address[3],bytes)", _data, _addrData, _callData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.logBoost(0, msg.sender, _data[0], ratioBefore, ratioAfter); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).transfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } }
Bots call this method to repay for user when conditions are met If the contract ownes gas token it will try and use it for gas price reduction _data Amount and exchange data [amount, minPrice, exchangeType, gasCost, 0xPrice] _addrData cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] _callData 0x callData _user The actual address that owns the Compound position
function repayFor( bytes memory _callData, address _user ) public payable onlyApproved { if (gasToken.balanceOf(address(this)) >= BOOST_GAS_TOKEN) { gasToken.free(BOOST_GAS_TOKEN); } (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); uint gasCost = calcGasCost(REPAY_GAS_COST); _data[4] = gasCost; _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature("repayWithLoan(uint256[5],address[3],bytes)", _data, _addrData, _callData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); returnEth(); logger.logRepay(0, msg.sender, _data[0], ratioBefore, ratioAfter); }
15,814,099
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./TimeLockPool.sol"; contract TimeLockNonTransferablePool is TimeLockPool { constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration, uint256 _maxBonus, uint256 _maxLockDuration ) TimeLockPool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration, _maxBonus, _maxLockDuration) { } // disable transfers function _transfer(address _from, address _to, uint256 _amount) internal pure override { revert("NON_TRANSFERABLE"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.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 { using Counters for Counters.Counter; mapping(address => Counters.Counter) 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 { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-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) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-ERC20Permit.sol"; import "../../../utils/math/Math.sol"; import "../../../utils/math/SafeCast.sol"; import "../../../utils/cryptography/ECDSA.sol"; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { return _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); return _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface ITimeLockPool { function deposit(uint256 _amount, uint256 _duration, address _receiver) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IBasePool { function distributeRewards(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IAbstractRewards { /** * @dev Returns the total amount of rewards a given address is able to withdraw. * @param account Address of a reward recipient * @return A uint256 representing the rewards `account` can withdraw */ function withdrawableRewardsOf(address account) external view returns (uint256); /** * @dev View the amount of funds that an address has withdrawn. * @param account The address of a token holder. * @return The amount of funds that `account` has withdrawn. */ function withdrawnRewardsOf(address account) external view returns (uint256); /** * @dev View the amount of funds that an address has earned in total. * accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account) * = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER * @param account The address of a token holder. * @return The amount of funds that `account` has earned in total. */ function cumulativeRewardsOf(address account) external view returns (uint256); /** * @dev This event emits when new funds are distributed * @param by the address of the sender who distributed funds * @param rewardsDistributed the amount of funds received for distribution */ event RewardsDistributed(address indexed by, uint256 rewardsDistributed); /** * @dev This event emits when distributed funds are withdrawn by a token holder. * @param by the address of the receiver of funds * @param fundsWithdrawn the amount of funds that were withdrawn */ event RewardsWithdrawn(address indexed by, uint256 fundsWithdrawn); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; contract TokenSaver is AccessControlEnumerable { using SafeERC20 for IERC20; bytes32 public constant TOKEN_SAVER_ROLE = keccak256("TOKEN_SAVER_ROLE"); event TokenSaved(address indexed by, address indexed receiver, address indexed token, uint256 amount); modifier onlyTokenSaver() { require(hasRole(TOKEN_SAVER_ROLE, _msgSender()), "TokenSaver.onlyTokenSaver: permission denied"); _; } constructor() { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function saveToken(address _token, address _receiver, uint256 _amount) external onlyTokenSaver { IERC20(_token).safeTransfer(_receiver, _amount); emit TokenSaved(_msgSender(), _receiver, _token, _amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "../interfaces/IBasePool.sol"; import "../interfaces/ITimeLockPool.sol"; import "./AbstractRewards.sol"; import "./TokenSaver.sol"; abstract contract BasePool is ERC20Votes, AbstractRewards, IBasePool, TokenSaver { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeCast for int256; IERC20 public immutable depositToken; IERC20 public immutable rewardToken; ITimeLockPool public immutable escrowPool; uint256 public immutable escrowPortion; // how much is escrowed 1e18 == 100% uint256 public immutable escrowDuration; // escrow duration in seconds event RewardsClaimed(address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount); constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration ) ERC20Permit(_name) ERC20(_name, _symbol) AbstractRewards(balanceOf, totalSupply) { require(_escrowPortion <= 1e18, "BasePool.constructor: Cannot escrow more than 100%"); require(_depositToken != address(0), "BasePool.constructor: Deposit token must be set"); depositToken = IERC20(_depositToken); rewardToken = IERC20(_rewardToken); escrowPool = ITimeLockPool(_escrowPool); escrowPortion = _escrowPortion; escrowDuration = _escrowDuration; if(_rewardToken != address(0) && _escrowPool != address(0)) { IERC20(_rewardToken).safeApprove(_escrowPool, type(uint256).max); } } function _mint(address _account, uint256 _amount) internal virtual override { super._mint(_account, _amount); _correctPoints(_account, -(_amount.toInt256())); } function _burn(address _account, uint256 _amount) internal virtual override { super._burn(_account, _amount); _correctPoints(_account, _amount.toInt256()); } function _transfer(address _from, address _to, uint256 _value) internal virtual override { super._transfer(_from, _to, _value); _correctPointsForTransfer(_from, _to, _value); } function distributeRewards(uint256 _amount) external override { rewardToken.safeTransferFrom(_msgSender(), address(this), _amount); _distributeRewards(_amount); } function claimRewards(address _receiver) external { uint256 rewardAmount = _prepareCollect(_msgSender()); uint256 escrowedRewardAmount = rewardAmount * escrowPortion / 1e18; uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount; if(escrowedRewardAmount != 0 && address(escrowPool) != address(0)) { escrowPool.deposit(escrowedRewardAmount, escrowDuration, _receiver); } // ignore dust if(nonEscrowedRewardAmount > 1) { rewardToken.safeTransfer(_receiver, nonEscrowedRewardAmount); } emit RewardsClaimed(_msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../interfaces/IAbstractRewards.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /** * @dev Based on: https://github.com/indexed-finance/dividends/blob/master/contracts/base/AbstractDividends.sol * Renamed dividends to rewards. * @dev (OLD) Many functions in this contract were taken from this repository: * https://github.com/atpar/funds-distribution-token/blob/master/contracts/FundsDistributionToken.sol * which is an example implementation of ERC 2222, the draft for which can be found at * https://github.com/atpar/funds-distribution-token/blob/master/EIP-DRAFT.md * * This contract has been substantially modified from the original and does not comply with ERC 2222. * Many functions were renamed as "rewards" rather than "funds" and the core functionality was separated * into this abstract contract which can be inherited by anything tracking ownership of reward shares. */ abstract contract AbstractRewards is IAbstractRewards { using SafeCast for uint128; using SafeCast for uint256; using SafeCast for int256; /* ======== Constants ======== */ uint128 public constant POINTS_MULTIPLIER = type(uint128).max; /* ======== Internal Function References ======== */ function(address) view returns (uint256) private immutable getSharesOf; function() view returns (uint256) private immutable getTotalShares; /* ======== Storage ======== */ uint256 public pointsPerShare; mapping(address => int256) public pointsCorrection; mapping(address => uint256) public withdrawnRewards; constructor( function(address) view returns (uint256) getSharesOf_, function() view returns (uint256) getTotalShares_ ) { getSharesOf = getSharesOf_; getTotalShares = getTotalShares_; } /* ======== Public View Functions ======== */ /** * @dev Returns the total amount of rewards a given address is able to withdraw. * @param _account Address of a reward recipient * @return A uint256 representing the rewards `account` can withdraw */ function withdrawableRewardsOf(address _account) public view override returns (uint256) { return cumulativeRewardsOf(_account) - withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has withdrawn. * @param _account The address of a token holder. * @return The amount of rewards that `account` has withdrawn. */ function withdrawnRewardsOf(address _account) public view override returns (uint256) { return withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has earned in total. * @dev accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account) * = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER * @param _account The address of a token holder. * @return The amount of rewards that `account` has earned in total. */ function cumulativeRewardsOf(address _account) public view override returns (uint256) { return ((pointsPerShare * getSharesOf(_account)).toInt256() + pointsCorrection[_account]).toUint256() / POINTS_MULTIPLIER; } /* ======== Dividend Utility Functions ======== */ /** * @notice Distributes rewards to token holders. * @dev It reverts if the total shares is 0. * It emits the `RewardsDistributed` event if the amount to distribute is greater than 0. * About undistributed rewards: * In each distribution, there is a small amount which does not get distributed, * which is `(amount * POINTS_MULTIPLIER) % totalShares()`. * With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting * distributed in a distribution can be less than 1 (base unit). */ function _distributeRewards(uint256 _amount) internal { uint256 shares = getTotalShares(); require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero"); if (_amount > 0) { pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares); emit RewardsDistributed(msg.sender, _amount); } } /** * @notice Prepares collection of owed rewards * @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is * greater than 0. */ function _prepareCollect(address _account) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableRewardsOf(_account); if (_withdrawableDividend > 0) { withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend; emit RewardsWithdrawn(_account, _withdrawableDividend); } return _withdrawableDividend; } function _correctPointsForTransfer(address _from, address _to, uint256 _shares) internal { int256 _magCorrection = (pointsPerShare * _shares).toInt256(); pointsCorrection[_from] = pointsCorrection[_from] + _magCorrection; pointsCorrection[_to] = pointsCorrection[_to] - _magCorrection; } /** * @dev Increases or decreases the points correction for `account` by * `shares*pointsPerShare`. */ function _correctPoints(address _account, int256 _shares) internal { pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (int256(pointsPerShare))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./base/BasePool.sol"; import "./interfaces/ITimeLockPool.sol"; contract TimeLockPool is BasePool, ITimeLockPool { using Math for uint256; using SafeERC20 for IERC20; uint256 public immutable maxBonus; uint256 public immutable maxLockDuration; uint256 public constant MIN_LOCK_DURATION = 10 minutes; mapping(address => Deposit[]) public depositsOf; struct Deposit { uint256 amount; uint64 start; uint64 end; } event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from); event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount); constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration, uint256 _maxBonus, uint256 _maxLockDuration ) BasePool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration) { require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration"); maxBonus = _maxBonus; maxLockDuration = _maxLockDuration; } function deposit(uint256 _amount, uint256 _duration, address _receiver) external override { require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0"); // Don't allow locking > maxLockDuration uint256 duration = _duration.min(maxLockDuration); // Enforce min lockup duration to prevent flash loan or MEV transaction ordering duration = duration.max(MIN_LOCK_DURATION); depositToken.safeTransferFrom(_msgSender(), address(this), _amount); depositsOf[_receiver].push(Deposit({ amount: _amount, start: uint64(block.timestamp), end: uint64(block.timestamp) + uint64(duration) })); uint256 mintAmount = _amount * getMultiplier(duration) / 1e18; _mint(_receiver, mintAmount); emit Deposited(_amount, duration, _receiver, _msgSender()); } function withdraw(uint256 _depositId, address _receiver) external { require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist"); Deposit memory userDeposit = depositsOf[_msgSender()][_depositId]; require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon"); // No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18; // remove Deposit depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1]; depositsOf[_msgSender()].pop(); // burn pool shares _burn(_msgSender(), shareAmount); // return tokens depositToken.safeTransfer(_receiver, userDeposit.amount); emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount); } function getMultiplier(uint256 _lockDuration) public view returns(uint256) { return 1e18 + (maxBonus * _lockDuration / maxLockDuration); } function getTotalDeposit(address _account) public view returns(uint256) { uint256 total; for(uint256 i = 0; i < depositsOf[_account].length; i++) { total += depositsOf[_account][i].amount; } return total; } function getDepositsOf(address _account) public view returns(Deposit[] memory) { return depositsOf[_account]; } function getDepositsOfLength(address _account) public view returns(uint256) { return depositsOf[_account].length; } }
Prepares collection of owed rewards It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is greater than 0./
function _prepareCollect(address _account) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableRewardsOf(_account); if (_withdrawableDividend > 0) { withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend; emit RewardsWithdrawn(_account, _withdrawableDividend); } return _withdrawableDividend; }
86,399
pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./ExchangeWithOrionPool.sol"; import "./utils/orionpool/periphery/interfaces/IOrionPoolV2Router02Ext.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./libs/LibAtomic.sol"; contract ExchangeWithAtomic is ExchangeWithOrionPool { mapping(bytes32 => LibAtomic.LockOrder) public atomicSwaps; mapping(bytes32 => LibAtomic.RedeemInfo) public secrets; event AtomicLocked( address sender, address asset, bytes32 secretHash ); event AtomicRedeemed( address sender, address receiver, address asset, bytes secret ); event AtomicClaimed( address receiver, address asset, bytes secret ); event AtomicRefunded( address receiver, address asset, bytes32 secretHash ); function lockAtomic(LibAtomic.LockOrder memory swap) payable public nonReentrant { LibAtomic.doLockAtomic(swap, atomicSwaps, secrets, assetBalances, liabilities); require(checkPosition(swap.sender), "E1PA"); emit AtomicLocked(swap.sender, swap.asset, swap.secretHash); } function redeemAtomic(LibAtomic.RedeemOrder calldata order, bytes calldata secret) public nonReentrant { LibAtomic.doRedeemAtomic(order, secret, secrets, assetBalances, liabilities); require(checkPosition(order.sender), "E1PA"); emit AtomicRedeemed(order.sender, order.receiver, order.asset, secret); } function claimAtomic(address receiver, bytes calldata secret, bytes calldata matcherSignature) public nonReentrant { LibAtomic.LockOrder storage swap = LibAtomic.doClaimAtomic( receiver, secret, matcherSignature, _allowedMatcher, atomicSwaps, assetBalances, liabilities ); emit AtomicClaimed(receiver, swap.asset, secret); } function refundAtomic(bytes32 secretHash) public nonReentrant { LibAtomic.LockOrder storage swap = LibAtomic.doRefundAtomic(secretHash, atomicSwaps, assetBalances, liabilities); emit AtomicRefunded(swap.sender, swap.asset, swap.secretHash); } /* Error Codes E1: Insufficient Balance, flavor A - Atomic, PA - Position Atomic E17: Incorrect atomic secret, flavor: U - used, NF - not found, R - redeemed, E/NE - expired/not expired, ETH */ } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./Exchange.sol"; import "./interfaces/IPoolSwapCallback.sol"; import "./interfaces/IPoolFunctionality.sol"; import "./libs/LibPool.sol"; import "./utils/orionpool/periphery/interfaces/IOrionPoolV2Router02Ext.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract ExchangeWithOrionPool is Exchange, IPoolSwapCallback { using SafeERC20 for IERC20; address public _orionpoolRouter; mapping (address => bool) orionpoolAllowances; address public WETH; modifier initialized { require(address(_orionToken)!=address(0), "E16I"); require(_oracleAddress!=address(0), "E16I"); require(_allowedMatcher!=address(0), "E16I"); require(_orionpoolRouter!=address(0), "E16I"); _; } /** * @dev set basic Exchange params * @param orionToken - base token address * @param priceOracleAddress - adress of PriceOracle contract * @param allowedMatcher - address which has authorization to match orders * @param orionpoolRouter - OrionPool Functionality contract address for changes through orionpool */ function setBasicParams( address orionToken, address priceOracleAddress, address allowedMatcher, address orionpoolRouter ) public onlyOwner { _orionToken = IERC20(orionToken); _oracleAddress = priceOracleAddress; _allowedMatcher = allowedMatcher; _orionpoolRouter = orionpoolRouter; WETH = IPoolFunctionality(_orionpoolRouter).getWETH(); } //Important catch-all a function that should only accept ethereum and don't allow do something with it //We accept ETH there only from out router or wrapped ethereum contract. //If router sends some ETH to us - it's just swap completed, and we don't need to do something receive() external payable { require(msg.sender == _orionpoolRouter || msg.sender == WETH, "NPF"); } function safeAutoTransferFrom(address token, address from, address to, uint value) override external { require(msg.sender == _orionpoolRouter, "Only _orionpoolRouter allowed"); SafeTransferHelper.safeAutoTransferFrom(WETH, token, from, to, value); } /** * @notice (partially) settle buy order with OrionPool as counterparty * @dev order and orionpool path are submitted, it is necessary to match them: check conditions in order for compliance filledPrice and filledAmount change tokens via OrionPool check that final price after exchange not worse than specified in order change balances on the contract respectively * @param order structure of buy side orderbuyOrderHash * @param filledAmount amount of purchaseable token * @param path array of assets addresses (each consequent asset pair is change pair) */ function fillThroughOrionPool( LibValidator.Order memory order, uint112 filledAmount, uint64 blockchainFee, address[] calldata path ) public nonReentrant { LibPool.OrderExecutionData memory tmp = LibPool.doFillThroughOrionPool( order, filledAmount, blockchainFee, path, _allowedMatcher, assetBalances, liabilities, _orionpoolRouter, filledAmounts ); require(checkPosition(order.senderAddress), tmp.isInContractTrade ? (order.buySide == 0 ? "E1PS" : "E1PB") : "E1PF"); emit NewTrade( order.senderAddress, address(1), order.baseAsset, order.quoteAsset, uint64(tmp.filledPrice), uint192(tmp.filledBase), uint192(tmp.filledQuote) ); } function swapThroughOrionPool( uint112 amount_spend, uint112 amount_receive, address[] calldata path, bool is_exact_spend ) public payable nonReentrant { bool isCheckPosition = LibPool.doSwapThroughOrionPool(amount_spend, amount_receive, path, is_exact_spend, assetBalances, liabilities, _orionpoolRouter); if (isCheckPosition) { require(checkPosition(msg.sender), "E1PS"); } } } pragma solidity >=0.6.2; interface IOrionPoolV2Router02Ext { function swapExactTokensForTokensAutoRoute( uint amountIn, uint amountOutMin, address[] calldata path, address to ) external payable returns (uint[] memory amounts); function swapTokensForExactTokensAutoRoute( uint amountOut, uint amountInMax, address[] calldata path, address to ) external payable returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * 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)); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./LibValidator.sol"; import "./LibExchange.sol"; library LibAtomic { using ECDSA for bytes32; struct LockOrder { address sender; address asset; uint64 amount; uint64 expiration; bytes32 secretHash; bool used; } struct ClaimOrder { address receiver; bytes32 secretHash; } struct RedeemOrder { address sender; address receiver; address claimReceiver; address asset; uint64 amount; uint64 expiration; bytes32 secretHash; bytes signature; } struct RedeemInfo { address sender; bytes secret; } function doLockAtomic(LockOrder memory swap, mapping(bytes32 => LockOrder) storage atomicSwaps, mapping(bytes32 => RedeemInfo) storage secrets, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) public { require(msg.sender == swap.sender, "E3C"); require(swap.expiration/1000 >= block.timestamp, "E17E"); require(secrets[swap.secretHash].sender == address(0), "E17R"); require(atomicSwaps[swap.secretHash].sender == address(0), "E17R"); if (msg.value > 0) { require(swap.asset == address(0), "E17ETH"); uint112 eth_sent = uint112(LibUnitConverter.baseUnitToDecimal(address(0), msg.value)); require(swap.amount == eth_sent, "E17ETA"); } else { LibExchange._updateBalance(swap.sender, swap.asset, -1*int(swap.amount), assetBalances, liabilities); require(assetBalances[swap.sender][swap.asset] >= 0, "E1A"); } atomicSwaps[swap.secretHash] = swap; } function doRedeemAtomic( LibAtomic.RedeemOrder calldata order, bytes calldata secret, mapping(bytes32 => RedeemInfo) storage secrets, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) public { require(msg.sender == order.receiver, "E3C"); require(secrets[order.secretHash].sender == address(0), "E17R"); require(getEthSignedAtomicOrderHash(order).recover(order.signature) == order.sender, "E2"); require(order.expiration/1000 >= block.timestamp, "E4A"); require(order.secretHash == keccak256(secret), "E17"); LibExchange._updateBalance(order.sender, order.asset, -1*int(order.amount), assetBalances, liabilities); LibExchange._updateBalance(order.receiver, order.asset, order.amount, assetBalances, liabilities); secrets[order.secretHash] = RedeemInfo(order.claimReceiver, secret); } function doClaimAtomic( address receiver, bytes calldata secret, bytes calldata matcherSignature, address allowedMatcher, mapping(bytes32 => LockOrder) storage atomicSwaps, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) public returns (LockOrder storage swap) { bytes32 secretHash = keccak256(secret); bytes32 coHash = getEthSignedClaimOrderHash(ClaimOrder(receiver, secretHash)); require(coHash.recover(matcherSignature) == allowedMatcher, "E2"); swap = atomicSwaps[secretHash]; require(swap.sender != address(0), "E17NF"); require(swap.expiration/1000 >= block.timestamp, "E17E"); require(!swap.used, "E17U"); swap.used = true; LibExchange._updateBalance(receiver, swap.asset, swap.amount, assetBalances, liabilities); } function doRefundAtomic( bytes32 secretHash, mapping(bytes32 => LockOrder) storage atomicSwaps, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) public returns(LockOrder storage swap) { swap = atomicSwaps[secretHash]; require(swap.sender != address(0x0), "E17NF"); require(swap.expiration/1000 < block.timestamp, "E17NE"); require(!swap.used, "E17U"); swap.used = true; LibExchange._updateBalance(swap.sender, swap.asset, int(swap.amount), assetBalances, liabilities); } function getEthSignedAtomicOrderHash(RedeemOrder calldata _order) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "atomicOrder", _order.sender, _order.receiver, _order.claimReceiver, _order.asset, _order.amount, _order.expiration, _order.secretHash ) ).toEthSignedMessageHash(); } function getEthSignedClaimOrderHash(ClaimOrder memory _order) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "claimOrder", _order.receiver, _order.secretHash ) ).toEthSignedMessageHash(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./utils/ReentrancyGuard.sol"; import "./libs/LibUnitConverter.sol"; import "./libs/LibValidator.sol"; import "./libs/LibExchange.sol"; import "./libs/MarginalFunctionality.sol"; import "./libs/SafeTransferHelper.sol"; import "./OrionVault.sol"; /** * @title Exchange * @dev Exchange contract for the Orion Protocol * @author @wafflemakr */ /* Overflow safety: We do not use SafeMath and control overflows by not accepting large ints on input. Balances inside contract are stored as int192. Allowed input amounts are int112 or uint112: it is enough for all practically used tokens: for instance if decimal unit is 1e18, int112 allow to encode up to 2.5e15 decimal units. That way adding/subtracting any amount from balances won't overflow, since minimum number of operations to reach max int is practically infinite: ~1e24. Allowed prices are uint64. Note, that price is represented as price per 1e8 tokens. That means that amount*price always fit uint256, while amount*price/1e8 not only fit int192, but also can be added, subtracted without overflow checks: number of malicion operations to overflow ~1e13. */ contract Exchange is OrionVault, ReentrancyGuard { using LibValidator for LibValidator.Order; using SafeERC20 for IERC20; // Flags for updateOrders // All flags are explicit uint8 constant kSell = 0; uint8 constant kBuy = 1; // if 0 - then sell uint8 constant kCorrectMatcherFeeByOrderAmount = 2; // EVENTS event NewAssetTransaction( address indexed user, address indexed assetAddress, bool isDeposit, uint112 amount, uint64 timestamp ); event NewTrade( address indexed buyer, address indexed seller, address baseAsset, address quoteAsset, uint64 filledPrice, uint192 filledAmount, uint192 amountQuote ); // MAIN FUNCTIONS /** * @dev Since Exchange will work behind the Proxy contract it can not have constructor */ function initialize() public payable initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev set marginal settings * @param _collateralAssets - list of addresses of assets which may be used as collateral * @param _stakeRisk - risk coefficient for staken orion as uint8 (0=0, 255=1) * @param _liquidationPremium - premium for liquidator as uint8 (0=0, 255=1) * @param _priceOverdue - time after that price became outdated * @param _positionOverdue - time after that liabilities became overdue and may be liquidated */ function updateMarginalSettings( address[] calldata _collateralAssets, uint8 _stakeRisk, uint8 _liquidationPremium, uint64 _priceOverdue, uint64 _positionOverdue ) public onlyOwner { collateralAssets = _collateralAssets; stakeRisk = _stakeRisk; liquidationPremium = _liquidationPremium; priceOverdue = _priceOverdue; positionOverdue = _positionOverdue; } /** * @dev set risk coefficients for collateral assets * @param assets - list of assets * @param risks - list of risks as uint8 (0=0, 255=1) */ function updateAssetRisks(address[] calldata assets, uint8[] calldata risks) public onlyOwner { for (uint256 i; i < assets.length; i++) assetRisks[assets[i]] = risks[i]; } /** * @dev Deposit ERC20 tokens to the exchange contract * @dev User needs to approve token contract first * @param amount asset amount to deposit in its base unit */ function depositAsset(address assetAddress, uint112 amount) external { IERC20(assetAddress).safeTransferFrom( msg.sender, address(this), uint256(amount) ); generalDeposit(assetAddress, amount); } /** * @notice Deposit ETH to the exchange contract * @dev deposit event will be emitted with the amount in decimal format (10^8) * @dev balance will be stored in decimal format too */ function deposit() external payable { generalDeposit(address(0), uint112(msg.value)); } /** * @dev internal implementation of deposits */ function generalDeposit(address assetAddress, uint112 amount) internal { address user = msg.sender; bool wasLiability = assetBalances[user][assetAddress] < 0; int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); assetBalances[user][assetAddress] += safeAmountDecimal; if (amount > 0) emit NewAssetTransaction( user, assetAddress, true, uint112(safeAmountDecimal), uint64(block.timestamp) ); if (wasLiability) MarginalFunctionality.updateLiability( user, assetAddress, liabilities, uint112(safeAmountDecimal), assetBalances[user][assetAddress] ); } /** * @dev Withdrawal of remaining funds from the contract back to the address * @param assetAddress address of the asset to withdraw * @param amount asset amount to withdraw in its base unit */ function withdraw(address assetAddress, uint112 amount) external nonReentrant { int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); address user = msg.sender; assetBalances[user][assetAddress] -= safeAmountDecimal; require(assetBalances[user][assetAddress] >= 0, "E1w1"); //TODO require(checkPosition(user), "E1w2"); //TODO if (assetAddress == address(0)) { (bool success, ) = user.call{value: amount}(""); require(success, "E6w"); } else { IERC20(assetAddress).safeTransfer(user, amount); } emit NewAssetTransaction( user, assetAddress, false, uint112(safeAmountDecimal), uint64(block.timestamp) ); } /** * @dev Get asset balance for a specific address * @param assetAddress address of the asset to query * @param user user address to query */ function getBalance(address assetAddress, address user) public view returns (int192) { return assetBalances[user][assetAddress]; } /** * @dev Batch query of asset balances for a user * @param assetsAddresses array of addresses of the assets to query * @param user user address to query */ function getBalances(address[] memory assetsAddresses, address user) public view returns (int192[] memory balances) { balances = new int192[](assetsAddresses.length); for (uint256 i; i < assetsAddresses.length; i++) { balances[i] = assetBalances[user][assetsAddresses[i]]; } } /** * @dev Batch query of asset liabilities for a user * @param user user address to query */ function getLiabilities(address user) public view returns (MarginalFunctionality.Liability[] memory liabilitiesArray) { return liabilities[user]; } /** * @dev Return list of assets which can be used for collateral */ function getCollateralAssets() public view returns (address[] memory) { return collateralAssets; } /** * @dev get hash for an order * @dev we use order hash as order id to prevent double matching of the same order */ function getOrderHash(LibValidator.Order memory order) public pure returns (bytes32) { return order.getTypeValueHash(); } /** * @dev get filled amounts for a specific order */ function getFilledAmounts( bytes32 orderHash, LibValidator.Order memory order ) public view returns (int192 totalFilled, int192 totalFeesPaid) { totalFilled = int192(filledAmounts[orderHash]); //It is safe to convert here: filledAmounts is result of ui112 additions totalFeesPaid = int192( (uint256(order.matcherFee) * uint112(totalFilled)) / order.amount ); //matcherFee is u64; safe multiplication here } /** * @notice Settle a trade with two orders, filled price and amount * @dev 2 orders are submitted, it is necessary to match them: check conditions in orders for compliance filledPrice, filledAmountbuyOrderHash change balances on the contract respectively with buyer, seller, matcbuyOrderHashher * @param buyOrder structure of buy side orderbuyOrderHash * @param sellOrder structure of sell side order * @param filledPrice price at which the order was settled * @param filledAmount amount settled between orders */ struct UpdateOrderBalanceData { uint buyType; uint sellType; int buyIn; int sellIn; } function fillOrders( LibValidator.Order memory buyOrder, LibValidator.Order memory sellOrder, uint64 filledPrice, uint112 filledAmount ) public nonReentrant { // --- VARIABLES --- // // Amount of quote asset uint256 _amountQuote = (uint256(filledAmount) * filledPrice) / (10**8); require(_amountQuote < type(uint112).max, "E12G"); uint112 amountQuote = uint112(_amountQuote); // Order Hashes bytes32 buyOrderHash = buyOrder.getTypeValueHash(); bytes32 sellOrderHash = sellOrder.getTypeValueHash(); // --- VALIDATIONS --- // // Validate signatures using eth typed sign V1 require( LibValidator.checkOrdersInfo( buyOrder, sellOrder, msg.sender, filledAmount, filledPrice, block.timestamp, _allowedMatcher ), "E3G" ); // --- UPDATES --- // //updateFilledAmount filledAmounts[buyOrderHash] += filledAmount; //it is safe to add ui112 to each other to get i192 filledAmounts[sellOrderHash] += filledAmount; require(filledAmounts[buyOrderHash] <= buyOrder.amount, "E12B"); require(filledAmounts[sellOrderHash] <= sellOrder.amount, "E12S"); // Update User's balances UpdateOrderBalanceData memory data; (data.buyType, data.buyIn) = LibExchange.updateOrderBalanceDebit( buyOrder, filledAmount, amountQuote, kBuy | kCorrectMatcherFeeByOrderAmount, assetBalances, liabilities ); (data.sellType, data.sellIn) = LibExchange.updateOrderBalanceDebit( sellOrder, filledAmount, amountQuote, kSell | kCorrectMatcherFeeByOrderAmount, assetBalances, liabilities ); LibExchange.creditUserAssets(data.buyType, buyOrder.senderAddress, data.buyIn, buyOrder.baseAsset, assetBalances, liabilities); LibExchange.creditUserAssets(data.sellType, sellOrder.senderAddress, data.sellIn, sellOrder.quoteAsset, assetBalances, liabilities); require(checkPosition(buyOrder.senderAddress), "E1PB"); require(checkPosition(sellOrder.senderAddress), "E1PS"); emit NewTrade( buyOrder.senderAddress, sellOrder.senderAddress, buyOrder.baseAsset, buyOrder.quoteAsset, filledPrice, filledAmount, amountQuote ); } /** * @dev wrapper for LibValidator methods, may be deleted. */ function validateOrder(LibValidator.Order memory order) public pure returns (bool isValid) { isValid = order.isPersonalSign ? LibValidator.validatePersonal(order) : LibValidator.validateV3(order); } /** * @dev check user marginal position (compare assets and liabilities) * @return isPositive - boolean whether liabilities are covered by collateral or not */ function checkPosition(address user) public view returns (bool) { if (liabilities[user].length == 0) return true; return calcPosition(user).state == MarginalFunctionality.PositionState.POSITIVE; } /** * @dev internal methods which collect all variables used by MarginalFunctionality to one structure * @param user user address to query * @return UsedConstants - MarginalFunctionality.UsedConstants structure */ function getConstants(address user) internal view returns (MarginalFunctionality.UsedConstants memory) { return MarginalFunctionality.UsedConstants( user, _oracleAddress, address(_orionToken), positionOverdue, priceOverdue, stakeRisk, liquidationPremium ); } /** * @dev calc user marginal position (compare assets and liabilities) * @param user user address to query * @return position - MarginalFunctionality.Position structure */ function calcPosition(address user) public view returns (MarginalFunctionality.Position memory) { MarginalFunctionality.UsedConstants memory constants = getConstants( user ); return MarginalFunctionality.calcPosition( collateralAssets, liabilities, assetBalances, assetRisks, constants ); } /** * @dev method to cover some of overdue broker liabilities and get ORN in exchange same as liquidation or margin call * @param broker - broker which will be liquidated * @param redeemedAsset - asset, liability of which will be covered * @param amount - amount of covered asset */ function partiallyLiquidate( address broker, address redeemedAsset, uint112 amount ) public { MarginalFunctionality.UsedConstants memory constants = getConstants( broker ); MarginalFunctionality.partiallyLiquidate( collateralAssets, liabilities, assetBalances, assetRisks, constants, redeemedAsset, amount ); } /** * @dev revert on fallback function */ fallback() external { revert("E6"); } /* Error Codes E1: Insufficient Balance, flavor S - stake, L - liabilities, P - Position, B,S - buyer, seller E2: Invalid Signature, flavor B,S - buyer, seller E3: Invalid Order Info, flavor G - general, M - wrong matcher, M2 unauthorized matcher, As - asset mismatch, AmB/AmS - amount mismatch (buyer,seller), PrB/PrS - price mismatch(buyer,seller), D - direction mismatch, U - Unit Converter Error, C - caller mismatch E4: Order expired, flavor B,S - buyer,seller E5: Contract not active, E6: Transfer error E7: Incorrect state prior to liquidation E8: Liquidator doesn't satisfy requirements E9: Data for liquidation handling is outdated E10: Incorrect state after liquidation E11: Amount overflow E12: Incorrect filled amount, flavor G,B,S: general(overflow), buyer order overflow, seller order overflow E14: Authorization error, sfs - seizeFromStake E15: Wrong passed params E16: Underlying protection mechanism error, flavor: R, I, O: Reentrancy, Initialization, Ownable */ } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; interface IPoolSwapCallback { function safeAutoTransferFrom(address token, address from, address to, uint value) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; interface IPoolFunctionality { function doSwapThroughOrionPool( address user, uint112 amount_spend, uint112 amount_receive, address[] calldata path, bool is_exact_spend, address to ) external returns (uint amountOut, uint amountIn); function getWETH() external view returns (address); } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./LibValidator.sol"; import "./LibExchange.sol"; import "./LibUnitConverter.sol"; import "./SafeTransferHelper.sol"; import "../interfaces/IPoolFunctionality.sol"; library LibPool { function updateFilledAmount( LibValidator.Order memory order, uint112 filledBase, mapping(bytes32 => uint192) storage filledAmounts ) internal { bytes32 orderHash = LibValidator.getTypeValueHash(order); uint192 total_amount = filledAmounts[orderHash]; total_amount += filledBase; //it is safe to add ui112 to each other to get i192 require(total_amount >= filledBase, "E12B_0"); require(total_amount <= order.amount, "E12B"); filledAmounts[orderHash] = total_amount; } function refundChange(uint amountOut) internal { uint actualOutBaseUnit = uint(LibUnitConverter.decimalToBaseUnit(address(0), amountOut)); if (msg.value > actualOutBaseUnit) { SafeTransferHelper.safeTransferTokenOrETH(address(0), msg.sender, msg.value - actualOutBaseUnit); } } function doSwapThroughOrionPool( uint112 amount_spend, uint112 amount_receive, address[] calldata path, bool is_exact_spend, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities, address orionpoolRouter ) public returns(bool) { bool isInContractTrade = assetBalances[msg.sender][path[0]] > 0; bool isSentETHEnough; if (msg.value > 0) { uint112 eth_sent = uint112(LibUnitConverter.baseUnitToDecimal(address(0), msg.value)); if (path[0] == address(0) && eth_sent >= amount_spend) { isSentETHEnough = true; isInContractTrade = false; } else { LibExchange._updateBalance(msg.sender, address(0), eth_sent, assetBalances, liabilities); } } (uint amountOut, uint amountIn) = IPoolFunctionality(orionpoolRouter).doSwapThroughOrionPool( isInContractTrade || isSentETHEnough ? address(this) : msg.sender, amount_spend, amount_receive, path, is_exact_spend, isInContractTrade ? address(this) : msg.sender ); if (isSentETHEnough) { refundChange(amountOut); } else if (isInContractTrade) { LibExchange._updateBalance(msg.sender, path[0], -1*int256(amountOut), assetBalances, liabilities); LibExchange._updateBalance(msg.sender, path[path.length-1], int(amountIn), assetBalances, liabilities); return true; } return false; } // Just to avoid stack too deep error; struct OrderExecutionData { uint filledBase; uint filledQuote; uint filledPrice; uint amount_spend; uint amount_receive; uint amountQuote; bool isInContractTrade; bool isRetainFee; address to; } function calcAmounts( LibValidator.Order memory order, uint112 filledAmount, address[] calldata path, mapping(address => mapping(address => int192)) storage assetBalances ) internal returns (OrderExecutionData memory tmp) { tmp.amountQuote = uint(filledAmount) * order.price / (10**8); (tmp.amount_spend, tmp.amount_receive) = order.buySide == 0 ? (uint(filledAmount), tmp.amountQuote) : (tmp.amountQuote, uint(filledAmount)); tmp.isInContractTrade = path[0] == address(0) || assetBalances[order.senderAddress][path[0]] > 0; tmp.isRetainFee = !tmp.isInContractTrade && order.matcherFeeAsset == path[path.length-1]; tmp.to = (tmp.isInContractTrade || tmp.isRetainFee) ? address(this) : order.senderAddress; } function calcAmountInOutAfterSwap( OrderExecutionData memory tmp, LibValidator.Order memory order, uint64 blockchainFee, address[] calldata path, uint amountOut, uint amountIn, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) internal { bool isSeller = order.buySide == 0; (tmp.filledBase, tmp.filledQuote) = isSeller ? (amountOut, amountIn) : (amountIn, amountOut); tmp.filledPrice = tmp.filledQuote * (10**8) / tmp.filledBase; if (isSeller) { require(tmp.filledPrice >= order.price, "EX"); } else { require(tmp.filledPrice <= order.price, "EX"); } // Change fee only after order validation if (blockchainFee < order.matcherFee) order.matcherFee = blockchainFee; if (tmp.isInContractTrade) { (uint tradeType, int actualIn) = LibExchange.updateOrderBalanceDebit(order, uint112(tmp.filledBase), uint112(tmp.filledQuote), isSeller ? LibExchange.kSell : LibExchange.kBuy, assetBalances, liabilities); LibExchange.creditUserAssets(tradeType, order.senderAddress, actualIn, path[path.length-1], assetBalances, liabilities); } else { _payMatcherFee(order, assetBalances, liabilities); if (tmp.isRetainFee) { LibExchange.creditUserAssets(1, order.senderAddress, int(amountIn), path[path.length-1], assetBalances, liabilities); } } } function doFillThroughOrionPool( LibValidator.Order memory order, uint112 filledAmount, uint64 blockchainFee, address[] calldata path, address allowedMatcher, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities, address orionpoolRouter, mapping(bytes32 => uint192) storage filledAmounts ) public returns (OrderExecutionData memory tmp){ LibValidator.checkOrderSingleMatch(order, msg.sender, allowedMatcher, filledAmount, block.timestamp, path); bool isSeller = order.buySide == 0; tmp = calcAmounts(order, filledAmount, path, assetBalances); try IPoolFunctionality(orionpoolRouter).doSwapThroughOrionPool( tmp.isInContractTrade ? address(this) : order.senderAddress, uint112(tmp.amount_spend), uint112(tmp.amount_receive), path, isSeller, tmp.to ) returns(uint amountOut, uint amountIn) { calcAmountInOutAfterSwap(tmp, order, blockchainFee, path, amountOut, amountIn, assetBalances, liabilities); } catch(bytes memory) { tmp.filledBase = 0; tmp.filledPrice = order.price; _payMatcherFee(order, assetBalances, liabilities); } updateFilledAmount(order, uint112(tmp.filledBase), filledAmounts); } function _payMatcherFee( LibValidator.Order memory order, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) internal { LibExchange._updateBalance(order.senderAddress, order.matcherFeeAsset, -1*int(order.matcherFee), assetBalances, liabilities); LibExchange._updateBalance(order.matcherAddress, order.matcherFeeAsset, int(order.matcherFee), assetBalances, liabilities); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; contract ReentrancyGuard { bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } modifier nonReentrant() { // Ensure mutex is unlocked require(!getStorageBool(REENTRANCY_MUTEX_POSITION), ERROR_REENTRANT); // Lock mutex before function call setStorageBool(REENTRANCY_MUTEX_POSITION,true); // Perform function call _; // Unlock mutex after function call setStorageBool(REENTRANCY_MUTEX_POSITION, false); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; library LibUnitConverter { using SafeMath for uint; /** @notice convert asset amount from8 decimals (10^8) to its base unit */ function decimalToBaseUnit(address assetAddress, uint amount) internal view returns(int112 baseValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(1 ether).div(10**8); // 18 decimals } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**decimals).div(10**8); } require(result < uint256(type(int112).max), "E3U"); baseValue = int112(result); } /** @notice convert asset amount from its base unit to 8 decimals (10^8) */ function baseUnitToDecimal(address assetAddress, uint amount) internal view returns(int112 decimalValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(10**8).div(1 ether); } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**8).div(10**decimals); } require(result < uint256(type(int112).max), "E3U"); decimalValue = int112(result); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; library LibValidator { using ECDSA for bytes32; string public constant DOMAIN_NAME = "Orion Exchange"; string public constant DOMAIN_VERSION = "1"; uint256 public constant CHAIN_ID = 1; bytes32 public constant DOMAIN_SALT = 0xf2d857f4a3edcb9b78b4d503bfe733db1e3f6cdc2b7971ee739626c97e86a557; bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(string name,string version,uint256 chainId,bytes32 salt)" ) ); bytes32 public constant ORDER_TYPEHASH = keccak256( abi.encodePacked( "Order(address senderAddress,address matcherAddress,address baseAsset,address quoteAsset,address matcherFeeAsset,uint64 amount,uint64 price,uint64 matcherFee,uint64 nonce,uint64 expiration,uint8 buySide)" ) ); bytes32 public constant DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(DOMAIN_NAME)), keccak256(bytes(DOMAIN_VERSION)), CHAIN_ID, DOMAIN_SALT ) ); struct Order { address senderAddress; address matcherAddress; address baseAsset; address quoteAsset; address matcherFeeAsset; uint64 amount; uint64 price; uint64 matcherFee; uint64 nonce; uint64 expiration; uint8 buySide; // buy or sell bool isPersonalSign; bytes signature; } /** * @dev validate order signature */ function validateV3(Order memory order) public pure returns (bool) { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, getTypeValueHash(order) ) ); return digest.recover(order.signature) == order.senderAddress; } /** * @return hash order */ function getTypeValueHash(Order memory _order) internal pure returns (bytes32) { return keccak256( abi.encode( ORDER_TYPEHASH, _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ); } /** * @dev basic checks of matching orders against each other */ function checkOrdersInfo( Order memory buyOrder, Order memory sellOrder, address sender, uint256 filledAmount, uint256 filledPrice, uint256 currentTime, address allowedMatcher ) public pure returns (bool success) { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); sellOrder.isPersonalSign ? require(validatePersonal(sellOrder), "E2SP") : require(validateV3(sellOrder), "E2S"); // Same matcher address require( buyOrder.matcherAddress == sender && sellOrder.matcherAddress == sender, "E3M" ); if(allowedMatcher != address(0)) { require(buyOrder.matcherAddress == allowedMatcher, "E3M2"); } // Check matching assets require( buyOrder.baseAsset == sellOrder.baseAsset && buyOrder.quoteAsset == sellOrder.quoteAsset, "E3As" ); // Check order amounts require(filledAmount <= buyOrder.amount, "E3AmB"); require(filledAmount <= sellOrder.amount, "E3AmS"); // Check Price values require(filledPrice <= buyOrder.price, "E3"); require(filledPrice >= sellOrder.price, "E3"); // Check Expiration Time. Convert to seconds first require(buyOrder.expiration/1000 >= currentTime, "E4B"); require(sellOrder.expiration/1000 >= currentTime, "E4S"); require( buyOrder.buySide==1 && sellOrder.buySide==0, "E3D"); success = true; } function getEthSignedOrderHash(Order memory _order) public pure returns (bytes32) { return keccak256( abi.encodePacked( "order", _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ).toEthSignedMessageHash(); } function validatePersonal(Order memory order) public pure returns (bool) { bytes32 digest = getEthSignedOrderHash(order); return digest.recover(order.signature) == order.senderAddress; } function checkOrderSingleMatch( Order memory buyOrder, address sender, address allowedMatcher, uint112 filledAmount, uint256 currentTime, address[] memory path ) internal pure { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); require(buyOrder.matcherAddress == sender && buyOrder.matcherAddress == allowedMatcher, "E3M2"); if(buyOrder.buySide==1){ require( buyOrder.baseAsset == path[path.length-1] && buyOrder.quoteAsset == path[0], "E3As" ); }else{ require( buyOrder.quoteAsset == path[path.length-1] && buyOrder.baseAsset == path[0], "E3As" ); } require(filledAmount <= buyOrder.amount, "E3AmB"); require(buyOrder.expiration/1000 >= currentTime, "E4B"); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MarginalFunctionality.sol"; import "./LibUnitConverter.sol"; import "./LibValidator.sol"; import "./SafeTransferHelper.sol"; library LibExchange { using SafeERC20 for IERC20; // Flags for updateOrders // All flags are explicit uint8 public constant kSell = 0; uint8 public constant kBuy = 1; // if 0 - then sell uint8 public constant kCorrectMatcherFeeByOrderAmount = 2; function _updateBalance(address user, address asset, int amount, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) internal returns (uint tradeType) { // 0 - in contract, 1 - from wallet int beforeBalance = int(assetBalances[user][asset]); int afterBalance = beforeBalance + amount; if (amount > 0 && beforeBalance < 0) { MarginalFunctionality.updateLiability(user, asset, liabilities, uint112(amount), int192(afterBalance)); } else if (beforeBalance >= 0 && afterBalance < 0){ if (asset != address(0)) { afterBalance += int(_tryDeposit(asset, uint(-1*afterBalance), user)); } // If we failed to deposit balance is still negative then we move user into liability if (afterBalance < 0) { setLiability(user, asset, int192(afterBalance), liabilities); } else { tradeType = beforeBalance > 0 ? 0 : 1; } } if (beforeBalance != afterBalance) { assetBalances[user][asset] = int192(afterBalance); } } /** * @dev method to add liability * @param user - user which created liability * @param asset - liability asset * @param balance - current negative balance */ function setLiability(address user, address asset, int192 balance, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) internal { liabilities[user].push( MarginalFunctionality.Liability({ asset : asset, timestamp : uint64(block.timestamp), outstandingAmount : uint192(- balance) }) ); } function _tryDeposit( address asset, uint amount, address user ) internal returns(uint) { uint256 amountInBase = uint256(LibUnitConverter.decimalToBaseUnit(asset, amount)); // Query allowance before trying to transferFrom if (IERC20(asset).balanceOf(user) >= amountInBase && IERC20(asset).allowance(user, address(this)) >= amountInBase) { SafeERC20.safeTransferFrom(IERC20(asset), user, address(this), amountInBase); return amount; } else { return 0; } } function creditUserAssets(uint tradeType, address user, int amount, address asset, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) internal { int beforeBalance = int(assetBalances[user][asset]); int remainingAmount = amount + beforeBalance; int sentAmount = 0; if (tradeType == 1 && remainingAmount > 0 && beforeBalance <= 0) { uint amountInBase = uint(LibUnitConverter.decimalToBaseUnit(asset, uint(remainingAmount))); uint contractBalance = asset == address(0) ? address(this).balance : IERC20(asset).balanceOf(address(this)); if (contractBalance >= amountInBase) { SafeTransferHelper.safeTransferTokenOrETH(asset, user, amountInBase); sentAmount = remainingAmount; } } int toUpdate = amount - sentAmount; if (toUpdate != 0) { _updateBalance(user, asset, toUpdate, assetBalances, liabilities); } } struct SwapBalanceChanges { int amountOut; address assetOut; int amountIn; address assetIn; } /** * @notice update user balances and send matcher fee * @param flags uint8, see constants for possible flags of order */ function updateOrderBalanceDebit( LibValidator.Order memory order, uint112 amountBase, uint112 amountQuote, uint8 flags, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => MarginalFunctionality.Liability[]) storage liabilities ) internal returns (uint tradeType, int actualIn) { bool isSeller = (flags & kBuy) == 0; { // Stack too deep bool isCorrectFee = ((flags & kCorrectMatcherFeeByOrderAmount) != 0); if (isCorrectFee) { // matcherFee: u64, filledAmount u128 => matcherFee*filledAmount fit u256 // result matcherFee fit u64 order.matcherFee = uint64( (uint256(order.matcherFee) * amountBase) / order.amount ); //rewrite in memory only } } if (amountBase > 0) { SwapBalanceChanges memory swap; (swap.amountOut, swap.amountIn) = isSeller ? (-1*int(amountBase), int(amountQuote)) : (-1*int(amountQuote), int(amountBase)); (swap.assetOut, swap.assetIn) = isSeller ? (order.baseAsset, order.quoteAsset) : (order.quoteAsset, order.baseAsset); uint feeTradeType = 1; if (order.matcherFeeAsset == swap.assetOut) { swap.amountOut -= order.matcherFee; } else if (order.matcherFeeAsset == swap.assetIn) { swap.amountIn -= order.matcherFee; } else { feeTradeType = _updateBalance(order.senderAddress, order.matcherFeeAsset, -1*int256(order.matcherFee), assetBalances, liabilities); } tradeType = feeTradeType & _updateBalance(order.senderAddress, swap.assetOut, swap.amountOut, assetBalances, liabilities); actualIn = swap.amountIn; _updateBalance(order.matcherAddress, order.matcherFeeAsset, order.matcherFee, assetBalances, liabilities); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../PriceOracleInterface.sol"; library MarginalFunctionality { // We have the following approach: when liability is created we store // timestamp and size of liability. If the subsequent trade will deepen // this liability or won't fully cover it timestamp will not change. // However once outstandingAmount is covered we check whether balance on // that asset is positive or not. If not, liability still in the place but // time counter is dropped and timestamp set to `now`. struct Liability { address asset; uint64 timestamp; uint192 outstandingAmount; } enum PositionState { POSITIVE, NEGATIVE, // weighted position below 0 OVERDUE, // liability is not returned for too long NOPRICE, // some assets has no price or expired INCORRECT // some of the basic requirements are not met: too many liabilities, no locked stake, etc } struct Position { PositionState state; int256 weightedPosition; // sum of weighted collateral minus liabilities int256 totalPosition; // sum of unweighted (total) collateral minus liabilities int256 totalLiabilities; // total liabilities value } // Constants from Exchange contract used for calculations struct UsedConstants { address user; address _oracleAddress; address _orionTokenAddress; uint64 positionOverdue; uint64 priceOverdue; uint8 stakeRisk; uint8 liquidationPremium; } /** * @dev method to multiply numbers with uint8 based percent numbers */ function uint8Percent(int192 _a, uint8 b) internal pure returns (int192 c) { int a = int256(_a); int d = 255; c = int192((a>65536) ? (a/d)*b : a*b/d ); } /** * @dev method to fetch asset prices in ORN tokens */ function getAssetPrice(address asset, address oracle) internal view returns (uint64 price, uint64 timestamp) { PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(oracle).assetPrices(asset); (price, timestamp) = (assetPriceData.price, assetPriceData.timestamp); } /** * @dev method to calc weighted and absolute collateral value * @notice it only count for assets in collateralAssets list, all other assets will add 0 to position. * @return outdated whether any price is outdated * @return weightedPosition in ORN * @return totalPosition in ORN */ function calcAssets( address[] storage collateralAssets, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, address user, address orionTokenAddress, address oracleAddress, uint64 priceOverdue ) internal view returns (bool outdated, int192 weightedPosition, int192 totalPosition) { uint256 collateralAssetsLength = collateralAssets.length; for(uint256 i = 0; i < collateralAssetsLength; i++) { address asset = collateralAssets[i]; if(assetBalances[user][asset]<0) continue; // will be calculated in calcLiabilities (uint64 price, uint64 timestamp) = (1e8, 0xfffffff000000000); if(asset != orionTokenAddress) { (price, timestamp) = getAssetPrice(asset, oracleAddress); } // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here uint8 specificRisk = assetRisks[asset]; int192 balance = assetBalances[user][asset]; int256 _assetValue = int256(balance)*price/1e8; int192 assetValue = int192(_assetValue); // Overflows logic holds here as well, except that N is the number of // operations for all assets if(assetValue>0) { weightedPosition += uint8Percent(assetValue, specificRisk); totalPosition += assetValue; outdated = outdated || ((timestamp + priceOverdue) < block.timestamp); } } return (outdated, weightedPosition, totalPosition); } /** * @dev method to calc liabilities * @return outdated whether any price is outdated * @return overdue whether any liability is overdue * @return weightedPosition weightedLiability == totalLiability in ORN * @return totalPosition totalLiability in ORN */ function calcLiabilities( mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, address user, address oracleAddress, uint64 positionOverdue, uint64 priceOverdue ) internal view returns (bool outdated, bool overdue, int192 weightedPosition, int192 totalPosition) { uint256 liabilitiesLength = liabilities[user].length; for(uint256 i = 0; i < liabilitiesLength; i++) { Liability storage liability = liabilities[user][i]; int192 balance = assetBalances[user][liability.asset]; (uint64 price, uint64 timestamp) = getAssetPrice(liability.asset, oracleAddress); // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here int192 liabilityValue = int192(int256(balance) * price / 1e8); weightedPosition += liabilityValue; //already negative since balance is negative totalPosition += liabilityValue; overdue = overdue || ((liability.timestamp + positionOverdue) < block.timestamp); outdated = outdated || ((timestamp + priceOverdue) < block.timestamp); } return (outdated, overdue, weightedPosition, totalPosition); } /** * @dev method to calc Position * @return result position structure */ function calcPosition( address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants ) public view returns (Position memory result) { (bool outdatedPrice, int192 weightedPosition, int192 totalPosition) = calcAssets( collateralAssets, assetBalances, assetRisks, constants.user, constants._orionTokenAddress, constants._oracleAddress, constants.priceOverdue ); (bool _outdatedPrice, bool overdue, int192 _weightedPosition, int192 _totalPosition) = calcLiabilities( liabilities, assetBalances, constants.user, constants._oracleAddress, constants.positionOverdue, constants.priceOverdue ); weightedPosition += _weightedPosition; totalPosition += _totalPosition; outdatedPrice = outdatedPrice || _outdatedPrice; if(_totalPosition<0) { result.totalLiabilities = _totalPosition; } if(weightedPosition<0) { result.state = PositionState.NEGATIVE; } if(outdatedPrice) { result.state = PositionState.NOPRICE; } if(overdue) { result.state = PositionState.OVERDUE; } result.weightedPosition = weightedPosition; result.totalPosition = totalPosition; } /** * @dev method removes liability */ function removeLiability( address user, address asset, mapping(address => Liability[]) storage liabilities ) public { uint256 length = liabilities[user].length; for (uint256 i = 0; i < length; i++) { if (liabilities[user][i].asset == asset) { if (length>1) { liabilities[user][i] = liabilities[user][length - 1]; } liabilities[user].pop(); break; } } } /** * @dev method update liability * @notice implement logic for outstandingAmount (see Liability description) */ function updateLiability(address user, address asset, mapping(address => Liability[]) storage liabilities, uint112 depositAmount, int192 currentBalance ) internal { if(currentBalance>=0) { removeLiability(user,asset,liabilities); } else { uint256 i; uint256 liabilitiesLength=liabilities[user].length; for(; i<liabilitiesLength-1; i++) { if(liabilities[user][i].asset == asset) break; } Liability storage liability = liabilities[user][i]; if(depositAmount>=liability.outstandingAmount) { liability.outstandingAmount = uint192(-currentBalance); liability.timestamp = uint64(block.timestamp); } else { liability.outstandingAmount -= depositAmount; } } } /** * @dev partially liquidate, that is cover some asset liability to get ORN from misbehavior broker */ function partiallyLiquidate(address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants, address redeemedAsset, uint112 amount) public { //Note: constants.user - is broker who will be liquidated Position memory initialPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require(initialPosition.state == PositionState.NEGATIVE || initialPosition.state == PositionState.OVERDUE , "E7"); address liquidator = msg.sender; require(assetBalances[liquidator][redeemedAsset]>=amount,"E8"); require(assetBalances[constants.user][redeemedAsset]<0,"E15"); assetBalances[liquidator][redeemedAsset] -= amount; assetBalances[constants.user][redeemedAsset] += amount; if(assetBalances[constants.user][redeemedAsset] >= 0) removeLiability(constants.user, redeemedAsset, liabilities); (uint64 price, uint64 timestamp) = getAssetPrice(redeemedAsset, constants._oracleAddress); require((timestamp + constants.priceOverdue) > block.timestamp, "E9"); //Price is outdated reimburseLiquidator( amount, price, liquidator, assetBalances, constants.liquidationPremium, constants.user, constants._orionTokenAddress ); Position memory finalPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require( int(finalPosition.state)<3 && //POSITIVE,NEGATIVE or OVERDUE (finalPosition.weightedPosition>initialPosition.weightedPosition), "E10");//Incorrect state position after liquidation if(finalPosition.state == PositionState.POSITIVE) require (finalPosition.weightedPosition<10e8,"Can not liquidate to very positive state"); } /** * @dev reimburse liquidator with ORN: first from stake, than from broker balance */ function reimburseLiquidator( uint112 amount, uint64 price, address liquidator, mapping(address => mapping(address => int192)) storage assetBalances, uint8 liquidationPremium, address user, address orionTokenAddress ) internal { int192 _orionAmount = int192(int256(amount)*price/1e8); _orionAmount += uint8Percent(_orionAmount, liquidationPremium); //Liquidation premium // There is only 100m Orion tokens, fits i64 require(_orionAmount == int64(_orionAmount), "E11"); int192 onBalanceOrion = assetBalances[user][orionTokenAddress]; require(onBalanceOrion >= _orionAmount, "E10"); assetBalances[user][orionTokenAddress] -= _orionAmount; assetBalances[liquidator][orionTokenAddress] += _orionAmount; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; import "../utils/orionpool/periphery/interfaces/IWETH.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; library SafeTransferHelper { function safeAutoTransferFrom(address weth, address token, address from, address to, uint value) internal { if (token == address(0)) { require(from == address(this), "TransferFrom: this"); IWETH(weth).deposit{value: value}(); assert(IWETH(weth).transfer(to, value)); } else { if (from == address(this)) { SafeERC20.safeTransfer(IERC20(token), to, value); } else { SafeERC20.safeTransferFrom(IERC20(token), from, to, value); } } } function safeAutoTransferTo(address weth, address token, address to, uint value) internal { if (address(this) != to) { if (token == address(0)) { IWETH(weth).withdraw(value); Address.sendValue(payable(to), value); } else { SafeERC20.safeTransfer(IERC20(token), to, value); } } } function safeTransferTokenOrETH(address token, address to, uint value) internal { if (address(this) != to) { if (token == address(0)) { Address.sendValue(payable(to), value); } else { SafeERC20.safeTransfer(IERC20(token), to, value); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./utils/Ownable.sol"; import "./ExchangeStorage.sol"; abstract contract OrionVault is ExchangeStorage, OwnableUpgradeSafe { enum StakePhase{ NOTSTAKED, LOCKED, RELEASING, READYTORELEASE, FROZEN } struct Stake { uint64 amount; // 100m ORN in circulation fits uint64 StakePhase phase; uint64 lastActionTimestamp; } uint64 constant releasingDuration = 3600*24; mapping(address => Stake) private stakingData; /** * @dev Returns locked or frozen stake balance only * @param user address */ function getLockedStakeBalance(address user) public view returns (uint256) { return stakingData[user].amount; } /** * @dev Request stake unlock for msg.sender * @dev If stake phase is LOCKED, that changes phase to RELEASING * @dev If stake phase is READYTORELEASE, that withdraws stake to balance * @dev Note, both unlock and withdraw is impossible if user has liabilities */ function requestReleaseStake() public { address user = _msgSender(); Stake storage stake = stakingData[user]; assetBalances[user][address(_orionToken)] += stake.amount; stake.amount = 0; stake.phase = StakePhase.NOTSTAKED; } /** * @dev Lock some orions from exchange balance sheet * @param amount orions in 1e-8 units to stake */ function lockStake(uint64 amount) public { address user = _msgSender(); require(assetBalances[user][address(_orionToken)]>amount, "E1S"); Stake storage stake = stakingData[user]; assetBalances[user][address(_orionToken)] -= amount; stake.amount += amount; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: 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: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./PriceOracleDataTypes.sol"; interface PriceOracleInterface is PriceOracleDataTypes { function assetPrices(address) external view returns (PriceDataOut memory); function givePrices(address[] calldata assetAddresses) external view returns (PriceDataOut[] memory); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface PriceOracleDataTypes { struct PriceDataOut { uint64 price; uint64 timestamp; } } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./Context.sol"; import "./Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./libs/MarginalFunctionality.sol"; // Base contract which contain state variable of the first version of Exchange // deployed on mainnet. Changes of the state variables should be introduced // not in that contract but down the inheritance chain, to allow safe upgrades // More info about safe upgrades here: // https://blog.openzeppelin.com/the-state-of-smart-contract-upgrades/#upgrade-patterns contract ExchangeStorage { //order -> filledAmount mapping(bytes32 => uint192) public filledAmounts; // Get user balance by address and asset address mapping(address => mapping(address => int192)) internal assetBalances; // List of assets with negative balance for each user mapping(address => MarginalFunctionality.Liability[]) public liabilities; // List of assets which can be used as collateral and risk coefficients for them address[] internal collateralAssets; mapping(address => uint8) public assetRisks; // Risk coefficient for locked ORN uint8 public stakeRisk; // Liquidation premium uint8 public liquidationPremium; // Delays after which price and position become outdated uint64 public priceOverdue; uint64 public positionOverdue; // Base orion tokens (can be locked on stake) IERC20 _orionToken; // Address of price oracle contract address _oracleAddress; // Address from which matching of orders is allowed address _allowedMatcher; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./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. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
Batch query of asset balances for a user assetsAddresses array of addresses of the assets to query user user address to query/
function getBalances(address[] memory assetsAddresses, address user) public view returns (int192[] memory balances) { balances = new int192[](assetsAddresses.length); for (uint256 i; i < assetsAddresses.length; i++) { balances[i] = assetBalances[user][assetsAddresses[i]]; } }
10,261,454
./full_match/80001/0x29D9F65B7ca0f498f9a77A5077634D0c1D3AB30A/sources/_marketnode/sigma_contexts/contracts/contexts/abstract/MNContext.sol
Returns current instrument type/
function getInstrumentType() public virtual view returns (InstrumentType){ return InstrumentType.ABSTRACT_CONTEXT; }
868,244
pragma solidity 0.5.16; import {DogeClaimManager} from "./DogeClaimManager.sol"; import {DogeErrorCodes} from "./DogeErrorCodes.sol"; import {DogeSuperblocks} from "./DogeSuperblocks.sol"; import {DogeMessageLibrary} from "./DogeParser/DogeMessageLibrary.sol"; import {IScryptChecker} from "./IScryptChecker.sol"; import {IScryptCheckerListener} from "./IScryptCheckerListener.sol"; // @dev - Manages a battle session between superblock submitter and challenger contract DogeBattleManager is DogeErrorCodes, IScryptCheckerListener { enum ChallengeState { Unchallenged, // Unchallenged submission Challenged, // Claims was challenged QueryMerkleRootHashes, // Challenger expecting block hashes RespondMerkleRootHashes, // Blcok hashes were received and verified QueryBlockHeader, // Challenger is requesting block headers RespondBlockHeader, // All block headers were received VerifyScryptHash, RequestScryptVerification, PendingScryptVerification, PendingVerification, // Pending superblock verification SuperblockVerified, // Superblock verified SuperblockFailed // Superblock not valid } enum BlockInfoStatus { Nonexistent, Uninitialized, Requested, ScryptHashPending, ScryptHashVerified, ScryptHashFailed } struct BlockInfo { bytes32 prevBlock; uint64 timestamp; uint32 bits; BlockInfoStatus status; bytes powBlockHeader; bytes32 scryptHash; } struct BattleSession { bytes32 id; bytes32 superblockHash; address submitter; address challenger; uint lastActionTimestamp; // Last action timestamp uint lastActionClaimant; // Number last action submitter uint lastActionChallenger; // Number last action challenger uint actionsCounter; // Counter session actions bytes32[] blockHashes; // Block hashes uint countBlockHeaderQueries; // Number of block header queries uint countBlockHeaderResponses; // Number of block header responses mapping (bytes32 => BlockInfo) blocksInfo; bytes32 pendingScryptHashId; ChallengeState challengeState; // Claim state } struct ScryptHashVerification { bytes32 sessionId; bytes32 blockSha256Hash; } mapping (bytes32 => BattleSession) public sessions; uint public sessionsCount = 0; uint public superblockDuration; // Superblock duration (in seconds) uint public superblockTimeout; // Timeout action (in seconds) // Pending Scrypt Hash verifications uint public numScryptHashVerifications; mapping (bytes32 => ScryptHashVerification) public scryptHashVerifications; // network that the stored blocks belong to DogeMessageLibrary.Network private net; // ScryptHash checker IScryptChecker public trustedScryptChecker; // Doge claim manager DogeClaimManager trustedDogeClaimManager; // Superblocks contract DogeSuperblocks trustedSuperblocks; event NewBattle(bytes32 superblockHash, bytes32 sessionId, address submitter, address challenger); event ChallengerConvicted(bytes32 superblockHash, bytes32 sessionId, address challenger); event SubmitterConvicted(bytes32 superblockHash, bytes32 sessionId, address submitter); event QueryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address submitter); event RespondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes32[] blockHashes); event QueryBlockHeader(bytes32 superblockHash, bytes32 sessionId, address submitter, bytes32 blockSha256Hash); event RespondBlockHeader(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes32 blockScryptHash, bytes blockHeader, bytes powBlockHeader); event RequestScryptHashValidation(bytes32 superblockHash, bytes32 sessionId, bytes32 blockScryptHash, bytes blockHeader, bytes32 proposalId, address submitter); event ResolvedScryptHashValidation(bytes32 superblockHash, bytes32 sessionId, bytes32 blockScryptHash, bytes32 blockSha256Hash, bytes32 proposalId, address challenger, bool valid); event ErrorBattle(bytes32 sessionId, uint err); modifier onlyFrom(address sender) { require(msg.sender == sender); _; } modifier onlyClaimant(bytes32 sessionId) { require(msg.sender == sessions[sessionId].submitter); _; } modifier onlyChallenger(bytes32 sessionId) { require(msg.sender == sessions[sessionId].challenger); _; } // @dev – Configures the contract managing superblocks battles // @param _network Network type to use for block difficulty validation // @param _superblocks Contract that manages superblocks // @param _superblockDuration Superblock duration (in seconds) // @param _superblockTimeout Time to wait for challenges (in seconds) constructor( DogeMessageLibrary.Network _network, DogeSuperblocks _superblocks, uint _superblockDuration, uint _superblockTimeout ) public { net = _network; trustedSuperblocks = _superblocks; superblockDuration = _superblockDuration; superblockTimeout = _superblockTimeout; } // @dev - sets ScryptChecker instance associated with this DogeClaimManager contract. // Once trustedScryptChecker has been set, it cannot be changed. // An address of 0x0 means trustedScryptChecker hasn't been set yet. // // @param _scryptChecker - address of the ScryptChecker contract to be associated with DogeClaimManager function setScryptChecker(IScryptChecker _scryptChecker) public { require(address(trustedScryptChecker) == address(0x0) && address(_scryptChecker) != address(0x0)); trustedScryptChecker = _scryptChecker; } function setDogeClaimManager(DogeClaimManager _dogeClaimManager) public { require(address(trustedDogeClaimManager) == address(0x0) && address(_dogeClaimManager) != address(0x0)); trustedDogeClaimManager = _dogeClaimManager; } // @dev - Start a battle session function beginBattleSession(bytes32 superblockHash, address submitter, address challenger) public onlyFrom(address(trustedDogeClaimManager)) returns (bytes32) { bytes32 sessionId = keccak256(abi.encode(superblockHash, msg.sender, sessionsCount)); BattleSession storage session = sessions[sessionId]; session.id = sessionId; session.superblockHash = superblockHash; session.submitter = submitter; session.challenger = challenger; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = 0; session.lastActionClaimant = 1; // Force challenger to start session.actionsCounter = 1; session.challengeState = ChallengeState.Challenged; sessionsCount += 1; emit NewBattle(superblockHash, sessionId, submitter, challenger); return sessionId; } // @dev - Challenger makes a query for superblock hashes function doQueryMerkleRootHashes(BattleSession storage session) internal returns (uint) { if (!hasDeposit(msg.sender, respondMerkleRootHashesCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if (session.challengeState == ChallengeState.Challenged) { session.challengeState = ChallengeState.QueryMerkleRootHashes; assert(msg.sender == session.challenger); (uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondMerkleRootHashesCost); if (err != ERR_SUPERBLOCK_OK) { return err; } return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - Challenger makes a query for superblock hashes function queryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId) public onlyChallenger(sessionId) { BattleSession storage session = sessions[sessionId]; uint err = doQueryMerkleRootHashes(session); if (err != ERR_SUPERBLOCK_OK) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; emit QueryMerkleRootHashes(superblockHash, sessionId, session.submitter); } } // @dev - Submitter sends hashes to verify superblock merkle root function doVerifyMerkleRootHashes(BattleSession storage session, bytes32[] memory blockHashes) internal returns (uint) { if (!hasDeposit(msg.sender, verifySuperblockCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } require(session.blockHashes.length == 0); if (session.challengeState == ChallengeState.QueryMerkleRootHashes) { (bytes32 merkleRoot, , , , bytes32 lastHash, , , , ) = getSuperblockInfo(session.superblockHash); if (lastHash != blockHashes[blockHashes.length - 1]) { return ERR_SUPERBLOCK_BAD_LASTBLOCK; } if (merkleRoot != DogeMessageLibrary.makeMerkle(blockHashes)) { return ERR_SUPERBLOCK_INVALID_MERKLE; } (uint err, ) = bondDeposit(session.superblockHash, msg.sender, verifySuperblockCost); if (err != ERR_SUPERBLOCK_OK) { return err; } session.blockHashes = blockHashes; session.challengeState = ChallengeState.RespondMerkleRootHashes; return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - For the submitter to respond to challenger queries function respondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, bytes32[] memory blockHashes) public onlyClaimant(sessionId) { BattleSession storage session = sessions[sessionId]; uint err = doVerifyMerkleRootHashes(session, blockHashes); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; // Map blocks to prevent a malicious challenger from requesting one that doesn't exist for (uint i = 0; i < blockHashes.length; ++i) { session.blocksInfo[blockHashes[i]].status = BlockInfoStatus.Uninitialized; } emit RespondMerkleRootHashes(superblockHash, sessionId, session.challenger, blockHashes); } } // @dev - Challenger makes a query for block header data for a hash function doQueryBlockHeader(BattleSession storage session, bytes32 blockHash) internal returns (uint) { if (!hasDeposit(msg.sender, respondBlockHeaderCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if (session.challengeState == ChallengeState.VerifyScryptHash) { skipScryptHashVerification(session); } // TODO: see if this condition is worth refactoring if ((session.countBlockHeaderQueries == 0 && session.challengeState == ChallengeState.RespondMerkleRootHashes) || (session.countBlockHeaderQueries > 0 && session.challengeState == ChallengeState.RespondBlockHeader)) { require(session.countBlockHeaderQueries < session.blockHashes.length); require(session.blocksInfo[blockHash].status == BlockInfoStatus.Uninitialized); (uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost); if (err != ERR_SUPERBLOCK_OK) { return err; } session.countBlockHeaderQueries += 1; session.blocksInfo[blockHash].status = BlockInfoStatus.Requested; session.challengeState = ChallengeState.QueryBlockHeader; return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - For the challenger to start a query function queryBlockHeader(bytes32 superblockHash, bytes32 sessionId, bytes32 blockHash) public onlyChallenger(sessionId) { BattleSession storage session = sessions[sessionId]; uint err = doQueryBlockHeader(session, blockHash); if (err != ERR_SUPERBLOCK_OK) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; emit QueryBlockHeader(superblockHash, sessionId, session.submitter, blockHash); } } // @dev - Verify that block timestamp is in the superblock timestamp interval function verifyTimestamp(bytes32 superblockHash, bytes memory blockHeader) internal view returns (bool) { uint blockTimestamp = DogeMessageLibrary.getTimestamp(blockHeader, 0); uint superblockTimestamp; (, , superblockTimestamp, , , , , , ) = getSuperblockInfo(superblockHash); // Block timestamp to be within the expected timestamp of the superblock return (blockTimestamp / superblockDuration <= superblockTimestamp / superblockDuration) && (blockTimestamp / superblockDuration >= superblockTimestamp / superblockDuration - 1); } // @dev - Generate request to verify block header scrypt hash function doVerifyScryptHash( bytes32 sessionId, bytes32 blockScryptHash, bytes32 blockSha256Hash, address submitter ) internal returns (bytes32) { numScryptHashVerifications += 1; bytes32 proposalId = keccak256(abi.encodePacked( blockScryptHash, submitter, numScryptHashVerifications )); scryptHashVerifications[proposalId] = ScryptHashVerification({ sessionId: sessionId, blockSha256Hash: blockSha256Hash }); return proposalId; } // @dev - Verify Dogecoin block AuxPoW function verifyBlockAuxPoW( BlockInfo storage blockInfo, bytes32 proposedBlockScryptHash, bytes memory blockHeader ) internal returns (uint, bytes memory) { (uint err, , bytes32 blockScryptHash, bool isMergeMined) = DogeMessageLibrary.verifyBlockHeader(blockHeader, 0, blockHeader.length, proposedBlockScryptHash); if (err != 0) { return (err, new bytes(0)); } bytes memory powBlockHeader = (isMergeMined) ? DogeMessageLibrary.sliceArray(blockHeader, blockHeader.length - 80, blockHeader.length) : DogeMessageLibrary.sliceArray(blockHeader, 0, 80); blockInfo.timestamp = DogeMessageLibrary.getTimestamp(blockHeader, 0); blockInfo.bits = DogeMessageLibrary.getBits(blockHeader, 0); blockInfo.prevBlock = DogeMessageLibrary.getHashPrevBlock(blockHeader, 0); blockInfo.scryptHash = blockScryptHash; blockInfo.powBlockHeader = powBlockHeader; return (ERR_SUPERBLOCK_OK, powBlockHeader); } // @dev - Verify block header sent by challenger function doVerifyBlockHeader( BattleSession storage session, bytes32 sessionId, bytes32 proposedBlockScryptHash, bytes memory blockHeader ) internal returns (uint, bytes memory) { // TODO: see if this should fund Scrypt verification if (!hasDeposit(msg.sender, respondBlockHeaderCost)) { return (ERR_SUPERBLOCK_MIN_DEPOSIT, new bytes(0)); } if (session.challengeState == ChallengeState.QueryBlockHeader) { bytes32 blockSha256Hash = bytes32(DogeMessageLibrary.dblShaFlipMem(blockHeader, 0, 80)); BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash]; if (blockInfo.status != BlockInfoStatus.Requested) { return (ERR_SUPERBLOCK_BAD_DOGE_STATUS, new bytes(0)); } if (!verifyTimestamp(session.superblockHash, blockHeader)) { return (ERR_SUPERBLOCK_BAD_TIMESTAMP, new bytes(0)); } (uint err, bytes memory powBlockHeader) = verifyBlockAuxPoW(blockInfo, proposedBlockScryptHash, blockHeader); if (err != ERR_SUPERBLOCK_OK) { return (err, new bytes(0)); } blockInfo.status = BlockInfoStatus.ScryptHashPending; (err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost); if (err != ERR_SUPERBLOCK_OK) { return (err, new bytes(0)); } bytes32 pendingScryptHashId = doVerifyScryptHash( sessionId, blockInfo.scryptHash, blockSha256Hash, session.submitter ); session.countBlockHeaderResponses += 1; session.challengeState = ChallengeState.VerifyScryptHash; session.pendingScryptHashId = pendingScryptHashId; return (ERR_SUPERBLOCK_OK, powBlockHeader); } return (ERR_SUPERBLOCK_BAD_STATUS, new bytes(0)); } // @dev - For the submitter to respond to challenger queries function respondBlockHeader( bytes32 superblockHash, bytes32 sessionId, bytes32 blockScryptHash, bytes memory blockHeader ) public onlyClaimant(sessionId) { BattleSession storage session = sessions[sessionId]; (uint err, bytes memory powBlockHeader) = doVerifyBlockHeader(session, sessionId, blockScryptHash, blockHeader); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; emit RespondBlockHeader(superblockHash, sessionId, session.challenger, blockScryptHash, blockHeader, powBlockHeader); } } // @dev - Notify submitter to start scrypt hash verification function doRequestScryptHashValidation( BattleSession storage session, bytes32 superblockHash, bytes32 sessionId, bytes32 blockSha256Hash ) internal returns (uint) { if (!hasDeposit(msg.sender, queryMerkleRootHashesCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if (session.challengeState == ChallengeState.VerifyScryptHash) { BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash]; if (blockInfo.status == BlockInfoStatus.ScryptHashPending) { (uint err, ) = bondDeposit(session.superblockHash, msg.sender, queryMerkleRootHashesCost); if (err != ERR_SUPERBLOCK_OK) { return err; } emit RequestScryptHashValidation(superblockHash, sessionId, blockInfo.scryptHash, blockInfo.powBlockHeader, session.pendingScryptHashId, session.submitter); session.challengeState = ChallengeState.RequestScryptVerification; return ERR_SUPERBLOCK_OK; } } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - Challenger requests to start scrypt hash verification function requestScryptHashValidation( bytes32 superblockHash, bytes32 sessionId, bytes32 blockSha256Hash ) public onlyChallenger(sessionId) { BattleSession storage session = sessions[sessionId]; uint err = doRequestScryptHashValidation(session, superblockHash, sessionId, blockSha256Hash); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; } } // @dev - Validate superblock information from last blocks function validateLastBlocks(BattleSession storage session) internal view returns (uint) { if (session.blockHashes.length <= 0) { return ERR_SUPERBLOCK_BAD_LASTBLOCK; } uint lastTimestamp; uint prevTimestamp; uint32 lastBits; bytes32 parentId; (, , lastTimestamp, prevTimestamp, , lastBits, parentId, , ) = getSuperblockInfo(session.superblockHash); bytes32 blockSha256Hash = session.blockHashes[session.blockHashes.length - 1]; if (session.blocksInfo[blockSha256Hash].timestamp != lastTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } if (session.blocksInfo[blockSha256Hash].bits != lastBits) { return ERR_SUPERBLOCK_BAD_BITS; } if (session.blockHashes.length > 1) { blockSha256Hash = session.blockHashes[session.blockHashes.length - 2]; if (session.blocksInfo[blockSha256Hash].timestamp != prevTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } } else { (, , lastTimestamp, , , , , , ) = getSuperblockInfo(parentId); if (lastTimestamp != prevTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } } return ERR_SUPERBLOCK_OK; } // @dev - Validate superblock accumulated work function validateProofOfWork(BattleSession storage session) internal view returns (uint) { uint accWork; uint parentWork; bytes32 parentId; bytes32 prevBlock; uint parentTimestamp; uint gpTimestamp; uint32 prevBits; (, accWork, , , , , parentId, , ) = getSuperblockInfo(session.superblockHash); (, parentWork, parentTimestamp, gpTimestamp, prevBlock, prevBits, , , ) = getSuperblockInfo(parentId); uint idx = 0; uint work; while (idx < session.blockHashes.length) { bytes32 blockSha256Hash = session.blockHashes[idx]; uint32 bits = session.blocksInfo[blockSha256Hash].bits; if (session.blocksInfo[blockSha256Hash].prevBlock != prevBlock) { return ERR_SUPERBLOCK_BAD_PARENT; } if (net != DogeMessageLibrary.Network.REGTEST) { uint32 newBits = DogeMessageLibrary.calculateDigishieldDifficulty( int64(parentTimestamp) - int64(gpTimestamp), prevBits); if (net == DogeMessageLibrary.Network.TESTNET && session.blocksInfo[blockSha256Hash].timestamp - parentTimestamp > 120) { newBits = 0x1e0fffff; } if (bits != newBits) { return ERR_SUPERBLOCK_BAD_BITS; } } work += DogeMessageLibrary.diffFromBits(session.blocksInfo[blockSha256Hash].bits); prevBlock = blockSha256Hash; prevBits = session.blocksInfo[blockSha256Hash].bits; gpTimestamp = parentTimestamp; parentTimestamp = session.blocksInfo[blockSha256Hash].timestamp; idx += 1; } if (net != DogeMessageLibrary.Network.REGTEST && parentWork + work != accWork) { return ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK; } return ERR_SUPERBLOCK_OK; } // @dev - Verify whether a superblock's data is consistent // Only should be called when all block headers were submitted function doVerifySuperblock(BattleSession storage session, bytes32 sessionId) internal returns (uint) { if (session.challengeState == ChallengeState.VerifyScryptHash) { skipScryptHashVerification(session); } if (session.challengeState == ChallengeState.PendingVerification) { uint err; err = validateLastBlocks(session); if (err != 0) { emit ErrorBattle(sessionId, err); return 2; } err = validateProofOfWork(session); if (err != 0) { emit ErrorBattle(sessionId, err); return 2; } return 1; } else if (session.challengeState == ChallengeState.SuperblockFailed) { return 2; } return 0; } // @dev - Perform final verification once all blocks were submitted function verifySuperblock(bytes32 sessionId) public { BattleSession storage session = sessions[sessionId]; uint status = doVerifySuperblock(session, sessionId); if (status == 1) { convictChallenger(sessionId, session.challenger, session.superblockHash); } else if (status == 2) { convictSubmitter(sessionId, session.submitter, session.superblockHash); } } // @dev - Trigger conviction if response is not received in time function timeout(bytes32 sessionId) public returns (uint) { BattleSession storage session = sessions[sessionId]; if (session.challengeState == ChallengeState.PendingScryptVerification) { emit ErrorBattle(sessionId, ERR_SUPERBLOCK_NO_TIMEOUT); return ERR_SUPERBLOCK_NO_TIMEOUT; } if (session.challengeState == ChallengeState.SuperblockFailed || (session.lastActionChallenger > session.lastActionClaimant && block.timestamp > session.lastActionTimestamp + superblockTimeout)) { convictSubmitter(sessionId, session.submitter, session.superblockHash); return ERR_SUPERBLOCK_OK; } else if (session.lastActionClaimant > session.lastActionChallenger && block.timestamp > session.lastActionTimestamp + superblockTimeout) { convictChallenger(sessionId, session.challenger, session.superblockHash); return ERR_SUPERBLOCK_OK; } emit ErrorBattle(sessionId, ERR_SUPERBLOCK_NO_TIMEOUT); return ERR_SUPERBLOCK_NO_TIMEOUT; } // @dev - To be called when a challenger is convicted function convictChallenger(bytes32 sessionId, address challenger, bytes32 superblockHash) internal { BattleSession storage session = sessions[sessionId]; sessionDecided(sessionId, superblockHash, session.submitter, session.challenger); disable(sessionId); emit ChallengerConvicted(superblockHash, sessionId, challenger); } // @dev - To be called when a submitter is convicted function convictSubmitter(bytes32 sessionId, address submitter, bytes32 superblockHash) internal { BattleSession storage session = sessions[sessionId]; sessionDecided(sessionId, superblockHash, session.challenger, session.submitter); disable(sessionId); emit SubmitterConvicted(superblockHash, sessionId, submitter); } // @dev - Disable session // It should be called only when either the submitter or the challenger were convicted. function disable(bytes32 sessionId) internal { delete sessions[sessionId]; } // @dev Update scrypt verification result function notifyScryptHashResult( BattleSession storage session, bytes32 blockSha256Hash, bool valid ) internal { BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash]; if (valid){ blockInfo.status = BlockInfoStatus.ScryptHashVerified; if (session.countBlockHeaderResponses == session.blockHashes.length) { session.challengeState = ChallengeState.PendingVerification; } else { session.challengeState = ChallengeState.RespondBlockHeader; } } else { blockInfo.status = BlockInfoStatus.ScryptHashFailed; session.challengeState = ChallengeState.SuperblockFailed; } } // @dev - Skip scrypt hash verification function skipScryptHashVerification(BattleSession storage session) internal { require(session.pendingScryptHashId != 0x0); bytes32 pendingScryptHashId = session.pendingScryptHashId; ScryptHashVerification storage verification = scryptHashVerifications[pendingScryptHashId]; require(verification.sessionId != 0x0); notifyScryptHashResult(session, verification.blockSha256Hash, true); delete scryptHashVerifications[pendingScryptHashId]; session.pendingScryptHashId = 0x0; } // @dev - Compare two 80-byte Doge block headers function compareBlockHeader(bytes memory left, bytes memory right) internal pure returns (int) { require(left.length == 80); require(right.length == 80); int a; int b; // Compare first 32 bytes assembly { a := mload(add(left, 0x20)) b := mload(add(right, 0x20)) } if (a != b) { return a - b; } // Compare next 32 bytes assembly { a := mload(add(left, 0x40)) b := mload(add(right, 0x40)) } if (a != b) { return a - b; } // Compare last 32 bytes assembly { a := mload(add(left, 0x50)) b := mload(add(right, 0x50)) } // Note: There's a 16 bytes overlap with previous 32 bytes chunk // But comparing full 32 bytes is faster/cheaper return a - b; } // @dev - To be called after scrypt verification is submitted function scryptSubmitted( bytes32 scryptChallengeId, bytes32 _scryptHash, bytes calldata _data, address _submitter ) external onlyFrom(address(trustedScryptChecker)) { require(_data.length == 80); ScryptHashVerification storage verification = scryptHashVerifications[scryptChallengeId]; BattleSession storage session = sessions[verification.sessionId]; require(session.pendingScryptHashId == scryptChallengeId); require(session.challengeState == ChallengeState.RequestScryptVerification); require(session.submitter == _submitter); BlockInfo storage blockInfo = session.blocksInfo[verification.blockSha256Hash]; require(blockInfo.status == BlockInfoStatus.ScryptHashPending); require(blockInfo.scryptHash == _scryptHash); require(compareBlockHeader(blockInfo.powBlockHeader, _data) == 0); session.challengeState = ChallengeState.PendingScryptVerification; session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; } // @dev - Update session state with scrypt hash verification result function doNotifyScryptVerificationResult(bytes32 scryptChallengeId, bool succeeded) internal { ScryptHashVerification storage verification = scryptHashVerifications[scryptChallengeId]; BattleSession storage session = sessions[verification.sessionId]; require(session.pendingScryptHashId == scryptChallengeId); require(session.challengeState == ChallengeState.PendingScryptVerification); BlockInfo storage blockInfo = session.blocksInfo[verification.blockSha256Hash]; require(blockInfo.status == BlockInfoStatus.ScryptHashPending); notifyScryptHashResult(session, verification.blockSha256Hash, succeeded); // Restart challenger timeout session.lastActionTimestamp = block.timestamp; emit ResolvedScryptHashValidation( session.superblockHash, verification.sessionId, blockInfo.scryptHash, verification.blockSha256Hash, scryptChallengeId, session.challenger, succeeded ); } // @dev - Scrypt verification succeeded function scryptVerified(bytes32 scryptChallengeId) external onlyFrom(address(trustedScryptChecker)) { doNotifyScryptVerificationResult(scryptChallengeId, true); } // @dev - Scrypt verification failed function scryptFailed(bytes32 scryptChallengeId) external onlyFrom(address(trustedScryptChecker)) { doNotifyScryptVerificationResult(scryptChallengeId, false); } // @dev - Check if a session's challenger did not respond before timeout function getChallengerHitTimeout(bytes32 sessionId) public view returns (bool) { BattleSession storage session = sessions[sessionId]; return (session.challengeState != ChallengeState.PendingScryptVerification && session.lastActionClaimant > session.lastActionChallenger && block.timestamp > session.lastActionTimestamp + superblockTimeout); } // @dev - Check if a session's submitter did not respond before timeout function getSubmitterHitTimeout(bytes32 sessionId) public view returns (bool) { BattleSession storage session = sessions[sessionId]; return (session.challengeState != ChallengeState.PendingScryptVerification && session.lastActionChallenger > session.lastActionClaimant && block.timestamp > session.lastActionTimestamp + superblockTimeout); } // @dev - Return Doge block hashes associated with a certain battle session function getDogeBlockHashes(bytes32 sessionId) public view returns (bytes32[] memory) { return sessions[sessionId].blockHashes; } // @dev - To be called when a battle sessions was decided function sessionDecided(bytes32 sessionId, bytes32 superblockHash, address winner, address loser) internal { trustedDogeClaimManager.sessionDecided(sessionId, superblockHash, winner, loser); } // @dev - Retrieve superblock information function getSuperblockInfo(bytes32 superblockHash) internal view returns ( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, address _submitter, DogeSuperblocks.Status _status ) { return trustedSuperblocks.getSuperblock(superblockHash); } // @dev - Verify whether a user has a certain amount of deposits or more function hasDeposit(address who, uint amount) internal view returns (bool) { return trustedDogeClaimManager.getDeposit(who) >= amount; } // @dev – locks up part of a user's deposit into a claim. function bondDeposit(bytes32 superblockHash, address account, uint amount) internal returns (uint, uint) { return trustedDogeClaimManager.bondDeposit(superblockHash, account, amount); } }
- Check if a session's submitter did not respond before timeout
function getSubmitterHitTimeout(bytes32 sessionId) public view returns (bool) { BattleSession storage session = sessions[sessionId]; return (session.challengeState != ChallengeState.PendingScryptVerification && session.lastActionChallenger > session.lastActionClaimant && block.timestamp > session.lastActionTimestamp + superblockTimeout); }
6,366,539
// SPDX-License-Identifier: MIT pragma solidity >=0.6.12; /// @title Claimable contract interface interface IClaimable { function owner() external view returns (address); function transferOwnership(address newOwner) external; function acceptOwnership() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IClaimable.sol"; /// @title Mintable Token interface interface IMintableToken is IERC20, IClaimable { function issue(address to, uint256 amount) external; function destroy(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import "./IMintableToken.sol"; /// @title The interface for mintable/burnable token governance. interface ITokenGovernance { // The address of the mintable ERC20 token. function token() external view returns (IMintableToken); /// @dev Mints new tokens. /// /// @param to Account to receive the new amount. /// @param amount Amount to increase the supply by. /// function mint(address to, uint256 amount) external; /// @dev Burns tokens from the caller. /// /// @param amount Amount to decrease the supply by. /// function burn(uint256 amount) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } /** * @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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ 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() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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; } /** * @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; } // 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 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 * ==== * * [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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @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[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @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[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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 // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol"; import { Token } from "../../token/Token.sol"; import { IPoolCollection } from "../../pools/interfaces/IPoolCollection.sol"; import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol"; /** * @dev Flash-loan recipient interface */ interface IFlashLoanRecipient { /** * @dev a flash-loan recipient callback after each the caller must return the borrowed amount and an additional fee */ function onFlashLoan( address caller, IERC20 erc20Token, uint256 amount, uint256 feeAmount, bytes memory data ) external; } /** * @dev Bancor Network interface */ interface IBancorNetwork is IUpgradeable { /** * @dev returns the set of all valid pool collections */ function poolCollections() external view returns (IPoolCollection[] memory); /** * @dev returns the most recent collection that was added to the pool collections set for a specific type */ function latestPoolCollection(uint16 poolType) external view returns (IPoolCollection); /** * @dev returns the set of all liquidity pools */ function liquidityPools() external view returns (Token[] memory); /** * @dev returns the respective pool collection for the provided pool */ function collectionByPool(Token pool) external view returns (IPoolCollection); /** * @dev returns whether the pool is valid */ function isPoolValid(Token pool) external view returns (bool); /** * @dev creates a new pool * * requirements: * * - the pool doesn't already exist */ function createPool(uint16 poolType, Token token) external; /** * @dev creates new pools * * requirements: * * - none of the pools already exists */ function createPools(uint16 poolType, Token[] calldata tokens) external; /** * @dev migrates a list of pools between pool collections * * notes: * * - invalid or incompatible pools will be skipped gracefully */ function migratePools(Token[] calldata pools) external; /** * @dev deposits liquidity for the specified provider and returns the respective pool token amount * * requirements: * * - the caller must have approved the network to transfer the tokens on its behalf (except for in the * native token case) */ function depositFor( address provider, Token pool, uint256 tokenAmount ) external payable returns (uint256); /** * @dev deposits liquidity for the current provider and returns the respective pool token amount * * requirements: * * - the caller must have approved the network to transfer the tokens on its behalf (except for in the * native token case) */ function deposit(Token pool, uint256 tokenAmount) external payable returns (uint256); /** * @dev deposits liquidity for the specified provider by providing an EIP712 typed signature for an EIP2612 permit * request and returns the respective pool token amount * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function depositForPermitted( address provider, Token pool, uint256 tokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /** * @dev deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns the * respective pool token amount * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function depositPermitted( Token pool, uint256 tokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /** * @dev initiates liquidity withdrawal * * requirements: * * - the caller must have approved the contract to transfer the pool token amount on its behalf */ function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount) external returns (uint256); /** * @dev initiates liquidity withdrawal by providing an EIP712 typed signature for an EIP2612 permit request * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function initWithdrawalPermitted( IPoolToken poolToken, uint256 poolTokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); /** * @dev cancels a withdrawal request * * requirements: * * - the caller must have already initiated a withdrawal and received the specified id */ function cancelWithdrawal(uint256 id) external; /** * @dev withdraws liquidity and returns the withdrawn amount * * requirements: * * - the provider must have already initiated a withdrawal and received the specified id * - the specified withdrawal request is eligible for completion * - the provider must have approved the network to transfer VBNT amount on its behalf, when withdrawing BNT * liquidity */ function withdraw(uint256 id) external returns (uint256); /** * @dev performs a trade by providing the input source amount * * requirements: * * - the caller must have approved the network to transfer the source tokens on its behalf (except for in the * native token case) */ function tradeBySourceAmount( Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary ) external payable; /** * @dev performs a trade by providing the input source amount and providing an EIP712 typed signature for an * EIP2612 permit request * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function tradeBySourceAmountPermitted( Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minReturnAmount, uint256 deadline, address beneficiary, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev performs a trade by providing the output target amount * * requirements: * * - the caller must have approved the network to transfer the source tokens on its behalf (except for in the * native token case) */ function tradeByTargetAmount( Token sourceToken, Token targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary ) external payable; /** * @dev performs a trade by providing the output target amount and providing an EIP712 typed signature for an * EIP2612 permit request and returns the target amount and fee * * requirements: * * - the caller must have provided a valid and unused EIP712 typed signature */ function tradeByTargetAmountPermitted( Token sourceToken, Token targetToken, uint256 targetAmount, uint256 maxSourceAmount, uint256 deadline, address beneficiary, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev provides a flash-loan * * requirements: * * - the recipient's callback must return *at least* the borrowed amount and fee back to the specified return address */ function flashLoan( Token token, uint256 amount, IFlashLoanRecipient recipient, bytes calldata data ) external; /** * @dev deposits liquidity during a migration */ function migrateLiquidity( Token token, address provider, uint256 amount, uint256 availableAmount, uint256 originalAmount ) external payable; /** * @dev withdraws pending network fees * * requirements: * * - the caller must have the ROLE_NETWORK_FEE_MANAGER privilege */ function withdrawNetworkFees(address recipient) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol"; import { Token } from "../../token/Token.sol"; error NotWhitelisted(); struct VortexRewards { // the percentage of converted BNT to be sent to the initiator of the burning event (in units of PPM) uint32 burnRewardPPM; // the maximum burn reward to be sent to the initiator of the burning event uint256 burnRewardMaxAmount; } /** * @dev Network Settings interface */ interface INetworkSettings is IUpgradeable { /** * @dev returns the protected tokens whitelist */ function protectedTokenWhitelist() external view returns (Token[] memory); /** * @dev checks whether a given token is whitelisted */ function isTokenWhitelisted(Token pool) external view returns (bool); /** * @dev returns the BNT funding limit for a given pool */ function poolFundingLimit(Token pool) external view returns (uint256); /** * @dev returns the minimum BNT trading liquidity required before the system enables trading in the relevant pool */ function minLiquidityForTrading() external view returns (uint256); /** * @dev returns the global network fee (in units of PPM) * * notes: * * - the network fee is a portion of the total fees from each pool */ function networkFeePPM() external view returns (uint32); /** * @dev returns the withdrawal fee (in units of PPM) */ function withdrawalFeePPM() external view returns (uint32); /** * @dev returns the default flash-loan fee (in units of PPM) */ function defaultFlashLoanFeePPM() external view returns (uint32); /** * @dev returns the flash-loan fee (in units of PPM) of a pool */ function flashLoanFeePPM(Token pool) external view returns (uint32); /** * @dev returns the vortex settings */ function vortexRewards() external view returns (VortexRewards memory); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IPoolToken } from "./IPoolToken.sol"; import { Token } from "../../token/Token.sol"; import { IVault } from "../../vaults/interfaces/IVault.sol"; // the BNT pool token manager role is required to access the BNT pool tokens bytes32 constant ROLE_BNT_POOL_TOKEN_MANAGER = keccak256("ROLE_BNT_POOL_TOKEN_MANAGER"); // the BNT manager role is required to request the BNT pool to mint BNT bytes32 constant ROLE_BNT_MANAGER = keccak256("ROLE_BNT_MANAGER"); // the vault manager role is required to request the BNT pool to burn BNT from the master vault bytes32 constant ROLE_VAULT_MANAGER = keccak256("ROLE_VAULT_MANAGER"); // the funding manager role is required to request or renounce funding from the BNT pool bytes32 constant ROLE_FUNDING_MANAGER = keccak256("ROLE_FUNDING_MANAGER"); /** * @dev BNT Pool interface */ interface IBNTPool is IVault { /** * @dev returns the BNT pool token contract */ function poolToken() external view returns (IPoolToken); /** * @dev returns the total staked BNT balance in the network */ function stakedBalance() external view returns (uint256); /** * @dev returns the current funding of given pool */ function currentPoolFunding(Token pool) external view returns (uint256); /** * @dev returns the available BNT funding for a given pool */ function availableFunding(Token pool) external view returns (uint256); /** * @dev converts the specified pool token amount to the underlying BNT amount */ function poolTokenToUnderlying(uint256 poolTokenAmount) external view returns (uint256); /** * @dev converts the specified underlying BNT amount to pool token amount */ function underlyingToPoolToken(uint256 bntAmount) external view returns (uint256); /** * @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified * amount */ function poolTokenAmountToBurn(uint256 bntAmountToDistribute) external view returns (uint256); /** * @dev mints BNT to the recipient * * requirements: * * - the caller must have the ROLE_BNT_MANAGER role */ function mint(address recipient, uint256 bntAmount) external; /** * @dev burns BNT from the vault * * requirements: * * - the caller must have the ROLE_VAULT_MANAGER role */ function burnFromVault(uint256 bntAmount) external; /** * @dev deposits BNT liquidity on behalf of a specific provider and returns the respective pool token amount * * requirements: * * - the caller must be the network contract * - BNT tokens must have been already deposited into the contract */ function depositFor( bytes32 contextId, address provider, uint256 bntAmount, bool isMigrating, uint256 originalVBNTAmount ) external returns (uint256); /** * @dev withdraws BNT liquidity on behalf of a specific provider and returns the withdrawn BNT amount * * requirements: * * - the caller must be the network contract * - VBNT token must have been already deposited into the contract */ function withdraw( bytes32 contextId, address provider, uint256 poolTokenAmount ) external returns (uint256); /** * @dev returns the withdrawn BNT amount */ function withdrawalAmount(uint256 poolTokenAmount) external view returns (uint256); /** * @dev requests BNT funding * * requirements: * * - the caller must have the ROLE_FUNDING_MANAGER role * - the token must have been whitelisted * - the request amount should be below the funding limit for a given pool * - the average rate of the pool must not deviate too much from its spot rate */ function requestFunding( bytes32 contextId, Token pool, uint256 bntAmount ) external; /** * @dev renounces BNT funding * * requirements: * * - the caller must have the ROLE_FUNDING_MANAGER role * - the token must have been whitelisted * - the average rate of the pool must not deviate too much from its spot rate */ function renounceFunding( bytes32 contextId, Token pool, uint256 bntAmount ) external; /** * @dev notifies the pool of accrued fees * * requirements: * * - the caller must be the network contract */ function onFeesCollected( Token pool, uint256 feeAmount, bool isTradeFee ) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { Fraction112 } from "../../utility/FractionLibrary.sol"; import { Token } from "../../token/Token.sol"; import { IPoolToken } from "./IPoolToken.sol"; struct PoolLiquidity { uint128 bntTradingLiquidity; // the BNT trading liquidity uint128 baseTokenTradingLiquidity; // the base token trading liquidity uint256 stakedBalance; // the staked balance } struct AverageRate { uint32 blockNumber; Fraction112 rate; } struct Pool { IPoolToken poolToken; // the pool token of the pool uint32 tradingFeePPM; // the trading fee (in units of PPM) bool tradingEnabled; // whether trading is enabled bool depositingEnabled; // whether depositing is enabled AverageRate averageRate; // the recent average rate uint256 depositLimit; // the deposit limit PoolLiquidity liquidity; // the overall liquidity in the pool } struct WithdrawalAmounts { uint256 totalAmount; uint256 baseTokenAmount; uint256 bntAmount; } // trading enabling/disabling reasons uint8 constant TRADING_STATUS_UPDATE_DEFAULT = 0; uint8 constant TRADING_STATUS_UPDATE_ADMIN = 1; uint8 constant TRADING_STATUS_UPDATE_MIN_LIQUIDITY = 2; struct TradeAmountAndFee { uint256 amount; // the source/target amount (depending on the context) resulting from the trade uint256 tradingFeeAmount; // the trading fee amount uint256 networkFeeAmount; // the network fee amount (always in units of BNT) } /** * @dev Pool Collection interface */ interface IPoolCollection is IVersioned { /** * @dev returns the type of the pool */ function poolType() external pure returns (uint16); /** * @dev returns the default trading fee (in units of PPM) */ function defaultTradingFeePPM() external view returns (uint32); /** * @dev returns all the pools which are managed by this pool collection */ function pools() external view returns (Token[] memory); /** * @dev returns the number of all the pools which are managed by this pool collection */ function poolCount() external view returns (uint256); /** * @dev returns whether a pool is valid */ function isPoolValid(Token pool) external view returns (bool); /** * @dev returns specific pool's data */ function poolData(Token pool) external view returns (Pool memory); /** * @dev returns the overall liquidity in the pool */ function poolLiquidity(Token pool) external view returns (PoolLiquidity memory); /** * @dev returns the pool token of the pool */ function poolToken(Token pool) external view returns (IPoolToken); /** * @dev converts the specified pool token amount to the underlying base token amount */ function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256); /** * @dev converts the specified underlying base token amount to pool token amount */ function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256); /** * @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified * amount */ function poolTokenAmountToBurn( Token pool, uint256 tokenAmountToDistribute, uint256 protocolPoolTokenAmount ) external view returns (uint256); /** * @dev creates a new pool * * requirements: * * - the caller must be the network contract * - the pool should have been whitelisted * - the pool isn't already defined in the collection */ function createPool(Token token) external; /** * @dev deposits base token liquidity on behalf of a specific provider and returns the respective pool token amount * * requirements: * * - the caller must be the network contract * - assumes that the base token has been already deposited in the vault */ function depositFor( bytes32 contextId, address provider, Token pool, uint256 tokenAmount ) external returns (uint256); /** * @dev handles some of the withdrawal-related actions and returns the withdrawn base token amount * * requirements: * * - the caller must be the network contract * - the caller must have approved the collection to transfer/burn the pool token amount on its behalf */ function withdraw( bytes32 contextId, address provider, Token pool, uint256 poolTokenAmount ) external returns (uint256); /** * @dev returns the amounts that would be returned if the position is currently withdrawn, * along with the breakdown of the base token and the BNT compensation */ function withdrawalAmounts(Token pool, uint256 poolTokenAmount) external view returns (WithdrawalAmounts memory); /** * @dev performs a trade by providing the source amount and returns the target amount and the associated fee * * requirements: * * - the caller must be the network contract */ function tradeBySourceAmount( bytes32 contextId, Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minReturnAmount ) external returns (TradeAmountAndFee memory); /** * @dev performs a trade by providing the target amount and returns the required source amount and the associated fee * * requirements: * * - the caller must be the network contract */ function tradeByTargetAmount( bytes32 contextId, Token sourceToken, Token targetToken, uint256 targetAmount, uint256 maxSourceAmount ) external returns (TradeAmountAndFee memory); /** * @dev returns the output amount and fee when trading by providing the source amount */ function tradeOutputAndFeeBySourceAmount( Token sourceToken, Token targetToken, uint256 sourceAmount ) external view returns (TradeAmountAndFee memory); /** * @dev returns the input amount and fee when trading by providing the target amount */ function tradeInputAndFeeByTargetAmount( Token sourceToken, Token targetToken, uint256 targetAmount ) external view returns (TradeAmountAndFee memory); /** * @dev notifies the pool of accrued fees * * requirements: * * - the caller must be the network contract */ function onFeesCollected(Token pool, uint256 feeAmount) external; /** * @dev migrates a pool to this pool collection * * requirements: * * - the caller must be the pool migrator contract */ function migratePoolIn(Token pool, Pool calldata data) external; /** * @dev migrates a pool from this pool collection * * requirements: * * - the caller must be the pool migrator contract */ function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol"; import { Token } from "../../token/Token.sol"; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { IOwned } from "../../utility/interfaces/IOwned.sol"; /** * @dev Pool Token interface */ interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable { /** * @dev returns the address of the reserve token */ function reserveToken() external view returns (Token); /** * @dev increases the token supply and sends the new tokens to the given account * * requirements: * * - the caller must be the owner of the contract */ function mint(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { EnumerableSetUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { ITokenGovernance } from "@bancor/token-governance/contracts/ITokenGovernance.sol"; import { IVersioned } from "../utility/interfaces/IVersioned.sol"; import { Upgradeable } from "../utility/Upgradeable.sol"; import { Utils, AccessDenied, DoesNotExist, AlreadyExists, InvalidParam } from "../utility/Utils.sol"; import { Time } from "../utility/Time.sol"; import { INetworkSettings, NotWhitelisted } from "../network/interfaces/INetworkSettings.sol"; import { IBancorNetwork } from "../network/interfaces/IBancorNetwork.sol"; import { IPoolToken } from "../pools/interfaces/IPoolToken.sol"; import { IBNTPool } from "../pools/interfaces/IBNTPool.sol"; import { Token } from "../token/Token.sol"; import { TokenLibrary, Signature } from "../token/TokenLibrary.sol"; import { IExternalRewardsVault } from "../vaults/interfaces/IExternalRewardsVault.sol"; import { IStandardRewards, ProgramData, StakeAmounts } from "./interfaces/IStandardRewards.sol"; /** * @dev Standard Rewards contract */ contract StandardRewards is IStandardRewards, ReentrancyGuardUpgradeable, Utils, Time, Upgradeable { using Address for address payable; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using TokenLibrary for Token; struct Rewards { uint32 lastUpdateTime; uint256 rewardPerToken; } struct ProviderRewards { uint256 rewardPerTokenPaid; uint256 pendingRewards; uint256 claimedRewards; uint256 stakedAmount; } struct RewardData { Token rewardsToken; uint256 amount; } struct ClaimData { uint256 reward; uint256 stakedAmount; } error ArrayNotUnique(); error InsufficientFunds(); error RewardsTooHigh(); error NativeTokenAmountMismatch(); error PoolMismatch(); error ProgramDisabled(); error ProgramInactive(); error RewardsTokenMismatch(); // since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases // where the total amount in the denominator is higher than the product of the rewards rate and staking duration. In // order to avoid this imprecision, we will amplify the reward rate by the units amount. uint256 private constant REWARD_RATE_FACTOR = 1e18; uint256 private constant INITIAL_PROGRAM_ID = 1; // the network contract IBancorNetwork private immutable _network; // the network settings contract INetworkSettings private immutable _networkSettings; // the address of the BNT token governance ITokenGovernance internal immutable _bntGovernance; // the BNT contract IERC20 private immutable _bnt; // the BNT pool token contract IPoolToken private immutable _bntPoolToken; // the address of the external rewards vault IExternalRewardsVault private immutable _externalRewardsVault; // the ID of the next created program uint256 internal _nextProgramId; // a mapping between providers and the program IDs of the program they are participating in mapping(address => EnumerableSetUpgradeable.UintSet) private _programIdsByProvider; // a mapping between program IDs and program data mapping(uint256 => ProgramData) internal _programs; // a mapping between pools and their latest programs mapping(Token => uint256) private _latestProgramIdByPool; // a mapping between programs and their respective rewards data mapping(uint256 => Rewards) internal _programRewards; // a mapping between providers, programs and their respective rewards data mapping(address => mapping(uint256 => ProviderRewards)) internal _providerRewards; // a mapping between programs and their total stakes mapping(uint256 => uint256) private _programStakes; // a mapping between reward tokens and total unclaimed rewards mapping(Token => uint256) internal _unclaimedRewards; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 8] private __gap; /** * @dev triggered when a program is created */ event ProgramCreated( Token indexed pool, uint256 indexed programId, Token indexed rewardsToken, uint256 totalRewards, uint32 startTime, uint32 endTime ); /** * @dev triggered when a program is terminated prematurely */ event ProgramTerminated(Token indexed pool, uint256 indexed programId, uint32 endTime, uint256 remainingRewards); /** * @dev triggered when a program is enabled/disabled */ event ProgramEnabled(Token indexed pool, uint256 indexed programId, bool status, uint256 remainingRewards); /** * @dev triggered when a provider joins a program */ event ProviderJoined( Token indexed pool, uint256 indexed programId, address indexed provider, uint256 poolTokenAmount, uint256 prevStake ); /** * @dev triggered when a provider leaves a program (even if partially) */ event ProviderLeft( Token indexed pool, uint256 indexed programId, address indexed provider, uint256 poolTokenAmount, uint256 remainingStake ); /** * @dev triggered when pending rewards are being claimed */ event RewardsClaimed(Token indexed pool, uint256 indexed programId, address indexed provider, uint256 amount); /** * @dev triggered when pending rewards are being staked */ event RewardsStaked(Token indexed pool, uint256 indexed programId, address indexed provider, uint256 amount); /** * @dev a "virtual" constructor that is only used to set immutable state variables */ constructor( IBancorNetwork initNetwork, INetworkSettings initNetworkSettings, ITokenGovernance initBNTGovernance, IBNTPool initBNTPool, IExternalRewardsVault initExternalRewardsVault ) validAddress(address(initNetwork)) validAddress(address(initNetworkSettings)) validAddress(address(initBNTGovernance)) validAddress(address(initBNTPool)) validAddress(address(initExternalRewardsVault)) { _network = initNetwork; _networkSettings = initNetworkSettings; _bntGovernance = initBNTGovernance; _bnt = initBNTGovernance.token(); _bntPoolToken = initBNTPool.poolToken(); _externalRewardsVault = initExternalRewardsVault; } /** * @dev fully initializes the contract and its parents */ function initialize() external initializer { __StandardRewards_init(); } // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __StandardRewards_init() internal onlyInitializing { __ReentrancyGuard_init(); __Upgradeable_init(); __StandardRewards_init_unchained(); } /** * @dev performs contract-specific initialization */ function __StandardRewards_init_unchained() internal onlyInitializing { _nextProgramId = INITIAL_PROGRAM_ID; } // solhint-enable func-name-mixedcase modifier uniqueArray(uint256[] calldata ids) { if (!_isArrayUnique(ids)) { revert ArrayNotUnique(); } _; } /** * @dev authorize the contract to receive the native token */ receive() external payable {} /** * @inheritdoc Upgradeable */ function version() public pure override(IVersioned, Upgradeable) returns (uint16) { return 1; } /** * @inheritdoc IStandardRewards */ function programIds() external view returns (uint256[] memory) { uint256 length = _nextProgramId - INITIAL_PROGRAM_ID; uint256[] memory ids = new uint256[](length); for (uint256 i = 0; i < length; i++) { ids[i] = i + INITIAL_PROGRAM_ID; } return ids; } /** * @inheritdoc IStandardRewards */ function programs(uint256[] calldata ids) external view uniqueArray(ids) returns (ProgramData[] memory) { uint256 length = ids.length; ProgramData[] memory list = new ProgramData[](length); for (uint256 i = 0; i < length; i++) { list[i] = _programs[ids[i]]; } return list; } /** * @inheritdoc IStandardRewards */ function providerProgramIds(address provider) external view returns (uint256[] memory) { return _programIdsByProvider[provider].values(); } /** * @inheritdoc IStandardRewards */ function programStake(uint256 id) external view returns (uint256) { return _programStakes[id]; } /** * @inheritdoc IStandardRewards */ function providerStake(address provider, uint256 id) external view returns (uint256) { return _providerRewards[provider][id].stakedAmount; } /** * @inheritdoc IStandardRewards */ function isProgramActive(uint256 id) external view returns (bool) { return _isProgramActive(_programs[id]); } /** * @inheritdoc IStandardRewards */ function isProgramEnabled(uint256 id) external view returns (bool) { return _isProgramEnabled(_programs[id]); } /** * @inheritdoc IStandardRewards */ function latestProgramId(Token pool) external view returns (uint256) { return _latestProgramIdByPool[pool]; } /** * @inheritdoc IStandardRewards */ function createProgram( Token pool, Token rewardsToken, uint256 totalRewards, uint32 startTime, uint32 endTime ) external validAddress(address(pool)) validAddress(address(rewardsToken)) greaterThanZero(totalRewards) onlyAdmin nonReentrant returns (uint256) { if (!(_time() <= startTime && startTime < endTime)) { revert InvalidParam(); } // ensure that no program exists for the specific pool if (_isProgramActive(_programs[_latestProgramIdByPool[pool]])) { revert AlreadyExists(); } IPoolToken poolToken; if (pool.isEqual(_bnt)) { poolToken = _bntPoolToken; } else { if (!_networkSettings.isTokenWhitelisted(pool)) { revert NotWhitelisted(); } poolToken = _network.collectionByPool(pool).poolToken(pool); } // ensure that the rewards were already deposited to the rewards vault uint256 unclaimedRewards = _unclaimedRewards[rewardsToken]; if (!rewardsToken.isEqual(_bnt)) { if (rewardsToken.balanceOf(address(_externalRewardsVault)) < unclaimedRewards + totalRewards) { revert InsufficientFunds(); } } uint256 id = _nextProgramId++; uint256 rewardRate = totalRewards / (endTime - startTime); _programs[id] = ProgramData({ id: id, pool: pool, poolToken: poolToken, rewardsToken: rewardsToken, isEnabled: true, startTime: startTime, endTime: endTime, rewardRate: rewardRate, remainingRewards: rewardRate * (endTime - startTime) }); // set the program as the latest program of the pool _latestProgramIdByPool[pool] = id; // increase the unclaimed rewards for the token by the total rewards in the new program _unclaimedRewards[rewardsToken] = unclaimedRewards + totalRewards; emit ProgramCreated({ pool: pool, programId: id, rewardsToken: rewardsToken, totalRewards: totalRewards, startTime: startTime, endTime: endTime }); return id; } /** * @inheritdoc IStandardRewards */ function terminateProgram(uint256 id) external onlyAdmin { ProgramData memory p = _programs[id]; _verifyProgramActive(p); // unset the program from being the latest program of the pool delete _latestProgramIdByPool[p.pool]; // reduce the unclaimed rewards for the token by the remaining rewards uint256 remainingRewards = _remainingRewards(p); _unclaimedRewards[p.rewardsToken] -= remainingRewards; // stop rewards accumulation _programs[id].endTime = _time(); emit ProgramTerminated(p.pool, id, p.endTime, remainingRewards); } /** * @inheritdoc IStandardRewards */ function enableProgram(uint256 id, bool status) external onlyAdmin { ProgramData storage p = _programs[id]; _verifyProgramExists(p); bool prevStatus = p.isEnabled; if (prevStatus == status) { return; } p.isEnabled = status; emit ProgramEnabled({ pool: p.pool, programId: id, status: status, remainingRewards: _remainingRewards(p) }); } /** * @inheritdoc IStandardRewards */ function join(uint256 id, uint256 poolTokenAmount) external greaterThanZero(poolTokenAmount) nonReentrant { ProgramData memory p = _programs[id]; _verifyProgramActiveAndEnabled(p); _join(msg.sender, p, poolTokenAmount, msg.sender); } /** * @inheritdoc IStandardRewards */ function joinPermitted( uint256 id, uint256 poolTokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external greaterThanZero(poolTokenAmount) nonReentrant { ProgramData memory p = _programs[id]; _verifyProgramActiveAndEnabled(p); // permit the amount the caller is trying to stake. Please note, that if the base token doesn't support // EIP2612 permit - either this call or the inner transferFrom will revert p.poolToken.permit(msg.sender, address(this), poolTokenAmount, deadline, v, r, s); _join(msg.sender, p, poolTokenAmount, msg.sender); } /** * @inheritdoc IStandardRewards */ function leave(uint256 id, uint256 poolTokenAmount) external greaterThanZero(poolTokenAmount) nonReentrant { ProgramData memory p = _programs[id]; _verifyProgramExists(p); _leave(msg.sender, p, poolTokenAmount); } /** * @inheritdoc IStandardRewards */ function depositAndJoin(uint256 id, uint256 tokenAmount) external payable greaterThanZero(tokenAmount) nonReentrant { ProgramData memory p = _programs[id]; _verifyProgramActiveAndEnabled(p); _depositAndJoin(msg.sender, p, tokenAmount); } /** * @inheritdoc IStandardRewards */ function depositAndJoinPermitted( uint256 id, uint256 tokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external greaterThanZero(tokenAmount) nonReentrant { ProgramData memory p = _programs[id]; _verifyProgramActiveAndEnabled(p); p.pool.permit(msg.sender, address(this), tokenAmount, deadline, Signature({ v: v, r: r, s: s })); _depositAndJoin(msg.sender, p, tokenAmount); } /** * @inheritdoc IStandardRewards */ function pendingRewards(address provider, uint256[] calldata ids) external view uniqueArray(ids) returns (uint256) { uint256 reward = 0; Token rewardsToken; for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; ProgramData memory p = _programs[id]; _verifyProgramExists(p); if (i == 0) { rewardsToken = p.rewardsToken; } if (p.rewardsToken != rewardsToken) { revert RewardsTokenMismatch(); } uint256 newRewardPerToken = _rewardPerToken(p, _programRewards[id]); ProviderRewards memory providerRewards = _providerRewards[provider][id]; reward += _pendingRewards(newRewardPerToken, providerRewards); } return reward; } /** * @inheritdoc IStandardRewards */ function claimRewards(uint256[] calldata ids) external uniqueArray(ids) nonReentrant returns (uint256) { RewardData memory rewardData = _claimRewards(msg.sender, ids, false); if (rewardData.amount == 0) { return 0; } _distributeRewards(msg.sender, rewardData); return rewardData.amount; } /** * @inheritdoc IStandardRewards */ function stakeRewards(uint256[] calldata ids) external uniqueArray(ids) nonReentrant returns (StakeAmounts memory) { RewardData memory rewardData = _claimRewards(msg.sender, ids, true); if (rewardData.amount == 0) { return StakeAmounts({ stakedRewardAmount: 0, poolTokenAmount: 0 }); } _distributeRewards(address(this), rewardData); // deposit provider's tokens to the network. Please note, that since we're staking rewards, then the deposit // should come from the contract itself, but the pool tokens should be sent to the provider directly uint256 poolTokenAmount = _deposit(msg.sender, rewardData.rewardsToken, rewardData.amount, address(this)); return StakeAmounts({ stakedRewardAmount: rewardData.amount, poolTokenAmount: poolTokenAmount }); } /** * @dev adds provider's stake to the program */ function _join( address provider, ProgramData memory p, uint256 poolTokenAmount, address payer ) private { // take a snapshot of the existing rewards (before increasing the stake) ProviderRewards storage data = _snapshotRewards(p, provider); // update both program and provider stakes _programStakes[p.id] += poolTokenAmount; uint256 prevStake = data.stakedAmount; data.stakedAmount = prevStake + poolTokenAmount; // unless the payer is the contract itself (in which case, no additional transfer is required), transfer the // tokens from the payer (we aren't using safeTransferFrom, since the PoolToken is a fully compliant ERC20 token // contract) if (payer != address(this)) { p.poolToken.transferFrom(payer, address(this), poolTokenAmount); } // add the program to the provider's program list _programIdsByProvider[provider].add(p.id); emit ProviderJoined({ pool: p.pool, programId: p.id, provider: provider, poolTokenAmount: poolTokenAmount, prevStake: prevStake }); } /** * @dev removes (some of) provider's stake from the program */ function _leave( address provider, ProgramData memory p, uint256 poolTokenAmount ) private { // take a snapshot of the existing rewards (before decreasing the stake) ProviderRewards storage data = _snapshotRewards(p, provider); // update both program and provider stakes _programStakes[p.id] -= poolTokenAmount; uint256 remainingStake = data.stakedAmount - poolTokenAmount; data.stakedAmount = remainingStake; // transfer the tokens to the provider (we aren't using safeTransfer, since the PoolToken is a fully // compliant ERC20 token contract) p.poolToken.transfer(provider, poolTokenAmount); // if the provider has removed all of its stake and there are no pending rewards - remove the program from the // provider's program list if (remainingStake == 0 && data.pendingRewards == 0) { _programIdsByProvider[provider].remove(p.id); } emit ProviderLeft({ pool: p.pool, programId: p.id, provider: provider, poolTokenAmount: poolTokenAmount, remainingStake: remainingStake }); } /** * @dev deposits provider's stake to the network and returns the received pool token amount */ function _deposit( address provider, Token pool, uint256 tokenAmount, address payer ) private returns (uint256) { uint256 poolTokenAmount; bool externalPayer = payer != address(this); if (pool.isNative()) { // unless the payer is the contract itself (e.g., during the staking process), in which case the native token // was already claimed and pending in the contract - verify and use the received native token from the sender if (externalPayer) { if (msg.value < tokenAmount) { revert NativeTokenAmountMismatch(); } } poolTokenAmount = _network.depositFor{ value: tokenAmount }(provider, pool, tokenAmount); // refund the caller for the remaining native token amount if (externalPayer && msg.value > tokenAmount) { payable(address(payer)).sendValue(msg.value - tokenAmount); } } else { if (msg.value > 0) { revert NativeTokenAmountMismatch(); } // unless the payer is the contract itself (e.g., during the staking process), in which case the tokens were // already claimed and pending in the contract - get the tokens from the provider if (externalPayer) { pool.safeTransferFrom(payer, address(this), tokenAmount); } pool.ensureApprove(address(_network), tokenAmount); poolTokenAmount = _network.depositFor(provider, pool, tokenAmount); } return poolTokenAmount; } /** * @dev deposits and adds provider's stake to the program */ function _depositAndJoin( address provider, ProgramData memory p, uint256 tokenAmount ) private { // deposit provider's tokens to the network and let the contract itself to claim the pool tokens so that it can // immediately add them to a program uint256 poolTokenAmount = _deposit(address(this), p.pool, tokenAmount, provider); // join the existing program, but ensure not to attempt to transfer the tokens from the provider by setting the // payer as the contract itself _join(provider, p, poolTokenAmount, address(this)); } /** * @dev claims rewards */ function _claimRewards( address provider, uint256[] calldata ids, bool stake ) private returns (RewardData memory) { RewardData memory rewardData = RewardData({ rewardsToken: Token(address(0)), amount: 0 }); for (uint256 i = 0; i < ids.length; i++) { ProgramData memory p = _programs[ids[i]]; _verifyProgramEnabled(p); if (i == 0) { rewardData.rewardsToken = p.rewardsToken; } if (p.rewardsToken != rewardData.rewardsToken) { revert RewardsTokenMismatch(); } ClaimData memory claimData = _claimRewards(provider, p); if (claimData.reward > 0) { uint256 remainingRewards = p.remainingRewards; // a sanity check that the reward amount doesn't exceed the remaining rewards per program if (remainingRewards < claimData.reward) { revert RewardsTooHigh(); } // decrease the remaining rewards per program _programs[ids[i]].remainingRewards = remainingRewards - claimData.reward; // collect same-reward token rewards rewardData.amount += claimData.reward; } // if the program is no longer active, has no stake left, and there are no pending rewards - remove the // program from the provider's program list if (!_isProgramActive(p) && claimData.stakedAmount == 0) { _programIdsByProvider[provider].remove(p.id); } if (stake) { emit RewardsStaked({ pool: p.pool, programId: p.id, provider: provider, amount: claimData.reward }); } else { emit RewardsClaimed({ pool: p.pool, programId: p.id, provider: provider, amount: claimData.reward }); } } // decrease the unclaimed rewards for the token by the total claimed rewards _unclaimedRewards[rewardData.rewardsToken] -= rewardData.amount; return rewardData; } /** * @dev claims rewards and returns the received and the pending reward amounts */ function _claimRewards(address provider, ProgramData memory p) internal returns (ClaimData memory) { ProviderRewards storage providerRewards = _snapshotRewards(p, provider); uint256 reward = providerRewards.pendingRewards; providerRewards.pendingRewards = 0; return ClaimData({ reward: reward, stakedAmount: providerRewards.stakedAmount }); } /** * @dev returns whether the specified program is active */ function _isProgramActive(ProgramData memory p) private view returns (bool) { uint32 currTime = _time(); return _doesProgramExist(p) && p.startTime <= currTime && currTime <= p.endTime && _latestProgramIdByPool[p.pool] == p.id; } /** * @dev returns whether the specified program is active */ function _isProgramEnabled(ProgramData memory p) private pure returns (bool) { return p.isEnabled; } /** * @dev returns whether or not a given program exists */ function _doesProgramExist(ProgramData memory p) private pure returns (bool) { return address(p.pool) != address(0); } /** * @dev verifies that a program exists */ function _verifyProgramExists(ProgramData memory p) private pure { if (!_doesProgramExist(p)) { revert DoesNotExist(); } } /** * @dev verifies that a program exists, and active */ function _verifyProgramActive(ProgramData memory p) private view { _verifyProgramExists(p); if (!_isProgramActive(p)) { revert ProgramInactive(); } } /** * @dev verifies that a program is enabled */ function _verifyProgramEnabled(ProgramData memory p) private pure { _verifyProgramExists(p); if (!p.isEnabled) { revert ProgramDisabled(); } } /** * @dev verifies that a program exists, active, and enabled */ function _verifyProgramActiveAndEnabled(ProgramData memory p) private view { _verifyProgramActive(p); _verifyProgramEnabled(p); } /** * @dev returns the remaining rewards of given program */ function _remainingRewards(ProgramData memory p) private view returns (uint256) { uint32 currTime = _time(); return p.endTime > currTime ? p.rewardRate * (p.endTime - currTime) : 0; } /** * @dev updates program and provider's rewards */ function _snapshotRewards(ProgramData memory p, address provider) private returns (ProviderRewards storage) { Rewards storage rewards = _programRewards[p.id]; uint256 newRewardPerToken = _rewardPerToken(p, rewards); if (newRewardPerToken != rewards.rewardPerToken) { rewards.rewardPerToken = newRewardPerToken; } uint32 newUpdateTime = uint32(Math.min(_time(), p.endTime)); if (rewards.lastUpdateTime < newUpdateTime) { rewards.lastUpdateTime = newUpdateTime; } ProviderRewards storage providerRewards = _providerRewards[provider][p.id]; uint256 newPendingRewards = _pendingRewards(newRewardPerToken, providerRewards); if (newPendingRewards != 0) { providerRewards.rewardPerTokenPaid = newRewardPerToken; providerRewards.pendingRewards = newPendingRewards; } return providerRewards; } /** * @dev calculates current reward per-token amount */ function _rewardPerToken(ProgramData memory p, Rewards memory rewards) private view returns (uint256) { uint256 currTime = _time(); if (currTime < p.startTime) { return 0; } uint256 totalStaked = _programStakes[p.id]; if (totalStaked == 0) { return rewards.rewardPerToken; } uint256 stakingEndTime = Math.min(currTime, p.endTime); uint256 stakingStartTime = Math.max(p.startTime, rewards.lastUpdateTime); return rewards.rewardPerToken + (((stakingEndTime - stakingStartTime) * p.rewardRate * REWARD_RATE_FACTOR) / totalStaked); } /** * @dev calculates provider's pending rewards */ function _pendingRewards(uint256 updatedRewardPerToken, ProviderRewards memory providerRewards) private pure returns (uint256) { return providerRewards.pendingRewards + (providerRewards.stakedAmount * (updatedRewardPerToken - providerRewards.rewardPerTokenPaid)) / REWARD_RATE_FACTOR; } /** * @dev distributes reward */ function _distributeRewards(address recipient, RewardData memory rewardData) private { if (rewardData.rewardsToken.isEqual(_bnt)) { _bntGovernance.mint(recipient, rewardData.amount); } else { _externalRewardsVault.withdrawFunds(rewardData.rewardsToken, payable(recipient), rewardData.amount); } } /** * @dev returns whether the specified array has duplicates */ function _isArrayUnique(uint256[] calldata ids) private pure returns (bool) { for (uint256 i = 0; i < ids.length; i++) { for (uint256 j = i + 1; j < ids.length; j++) { if (ids[i] == ids[j]) { return false; } } } return true; } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol"; import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol"; import { Token } from "../../token/Token.sol"; struct ProgramData { uint256 id; Token pool; IPoolToken poolToken; Token rewardsToken; bool isEnabled; uint32 startTime; uint32 endTime; uint256 rewardRate; uint256 remainingRewards; } struct StakeAmounts { uint256 stakedRewardAmount; uint256 poolTokenAmount; } interface IStandardRewards is IUpgradeable { /** * @dev returns all program ids */ function programIds() external view returns (uint256[] memory); /** * @dev returns program data for each specified program id */ function programs(uint256[] calldata ids) external view returns (ProgramData[] memory); /** * @dev returns all the program ids that the provider participates in */ function providerProgramIds(address provider) external view returns (uint256[] memory); /** * @dev returns the total staked amount in a specific program */ function programStake(uint256 id) external view returns (uint256); /** * @dev returns the total staked amount of a specific provider in a specific program */ function providerStake(address provider, uint256 id) external view returns (uint256); /** * @dev returns whether the specified program is active */ function isProgramActive(uint256 id) external view returns (bool); /** * @dev returns whether the specified program is enabled */ function isProgramEnabled(uint256 id) external view returns (bool); /** * @dev returns the ID of the latest program for a given pool (or 0 if no program is currently set) */ function latestProgramId(Token pool) external view returns (uint256); /** * @dev creates a program for a pool and returns its ID * * requirements: * * - the caller must be the admin of the contract * - the pool must not have an active program * - if the rewards token isn't the BNT token, then the rewards must have been deposited to the rewards vault */ function createProgram( Token pool, Token rewardsToken, uint256 totalRewards, uint32 startTime, uint32 endTime ) external returns (uint256); /** * @dev terminates a rewards program * * requirements: * * - the caller must be the admin of the contract * - the program must exist and be the active program for its pool */ function terminateProgram(uint256 id) external; /** * @dev enables or disables a program * * requirements: * * - the caller must be the admin of the contract */ function enableProgram(uint256 id, bool status) external; /** * @dev adds a provider to the program * * requirements: * * - the caller must have approved the contract to transfer pool tokens on its behalf */ function join(uint256 id, uint256 poolTokenAmount) external; /** * @dev adds provider's stake to the program by providing an EIP712 typed signature for an EIP2612 permit request * * requirements: * * - the caller must have specified a valid and unused EIP712 typed signature */ function joinPermitted( uint256 id, uint256 poolTokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev removes (some of) provider's stake from the program * * requirements: * * - the caller must have specified a valid and unused EIP712 typed signature */ function leave(uint256 id, uint256 poolTokenAmount) external; /** * @dev deposits and adds provider's stake to the program * * requirements: * * - the caller must have approved the network contract to transfer the tokens its behalf (except for in the * native token case) */ function depositAndJoin(uint256 id, uint256 tokenAmount) external payable; /** * @dev deposits and adds provider's stake to the program by providing an EIP712 typed signature for an EIP2612 * permit request * * requirements: * * - the caller must have specified a valid and unused EIP712 typed signature */ function depositAndJoinPermitted( uint256 id, uint256 tokenAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev returns provider's pending rewards * * requirements: * * - the specified program ids array needs to consist from unique and existing program ids with the same reward * token */ function pendingRewards(address provider, uint256[] calldata ids) external view returns (uint256); /** * @dev claims rewards and returns the claimed reward amount */ function claimRewards(uint256[] calldata ids) external returns (uint256); /** * @dev claims and stake rewards and returns the claimed reward amount and the received pool token amount * * requirements: * * - the specified program ids array needs to consist from unique and existing program ids with the same reward * token * - the rewards token must have been whitelisted with an existing pool */ function stakeRewards(uint256[] calldata ids) external returns (StakeAmounts memory); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev extends the SafeERC20 library with additional operations */ library SafeERC20Ex { using SafeERC20 for IERC20; /** * @dev ensures that the spender has sufficient allowance */ function ensureApprove( IERC20 token, address spender, uint256 amount ) internal { if (amount == 0) { return; } uint256 allowance = token.allowance(address(this), spender); if (allowance >= amount) { return; } if (allowance > 0) { token.safeApprove(spender, 0); } token.safeApprove(spender, amount); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions, * but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract */ interface Token { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import { SafeERC20Ex } from "./SafeERC20Ex.sol"; import { Token } from "./Token.sol"; struct Signature { uint8 v; bytes32 r; bytes32 s; } /** * @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens */ library TokenLibrary { using SafeERC20 for IERC20; using SafeERC20Ex for IERC20; error PermitUnsupported(); // the address that represents the native token reserve address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // the symbol that represents the native token string private constant NATIVE_TOKEN_SYMBOL = "ETH"; // the decimals for the native token uint8 private constant NATIVE_TOKEN_DECIMALS = 18; /** * @dev returns whether the provided token represents an ERC20 or the native token reserve */ function isNative(Token token) internal pure returns (bool) { return address(token) == NATIVE_TOKEN_ADDRESS; } /** * @dev returns the symbol of the native token/ERC20 token */ function symbol(Token token) internal view returns (string memory) { if (isNative(token)) { return NATIVE_TOKEN_SYMBOL; } return toERC20(token).symbol(); } /** * @dev returns the decimals of the native token/ERC20 token */ function decimals(Token token) internal view returns (uint8) { if (isNative(token)) { return NATIVE_TOKEN_DECIMALS; } return toERC20(token).decimals(); } /** * @dev returns the balance of the native token/ERC20 token */ function balanceOf(Token token, address account) internal view returns (uint256) { if (isNative(token)) { return account.balance; } return toIERC20(token).balanceOf(account); } /** * @dev transfers a specific amount of the native token/ERC20 token */ function safeTransfer( Token token, address to, uint256 amount ) internal { if (amount == 0) { return; } if (isNative(token)) { payable(to).transfer(amount); } else { toIERC20(token).safeTransfer(to, amount); } } /** * @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism * * note that the function does not perform any action if the native token is provided */ function safeTransferFrom( Token token, address from, address to, uint256 amount ) internal { if (amount == 0 || isNative(token)) { return; } toIERC20(token).safeTransferFrom(from, to, amount); } /** * @dev approves a specific amount of the native token/ERC20 token from a specific holder * * note that the function does not perform any action if the native token is provided */ function safeApprove( Token token, address spender, uint256 amount ) internal { if (isNative(token)) { return; } toIERC20(token).safeApprove(spender, amount); } /** * @dev ensures that the spender has sufficient allowance * * note that the function does not perform any action if the native token is provided */ function ensureApprove( Token token, address spender, uint256 amount ) internal { if (isNative(token)) { return; } toIERC20(token).ensureApprove(spender, amount); } /** * @dev performs an EIP2612 permit */ function permit( Token token, address owner, address spender, uint256 tokenAmount, uint256 deadline, Signature memory signature ) internal { if (isNative(token)) { revert PermitUnsupported(); } // permit the amount the owner is trying to deposit. Please note, that if the base token doesn't support // EIP2612 permit - either this call or the inner safeTransferFrom will revert IERC20Permit(address(token)).permit( owner, spender, tokenAmount, deadline, signature.v, signature.r, signature.s ); } /** * @dev compares between a token and another raw ERC20 token */ function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) { return toIERC20(token) == erc20Token; } /** * @dev utility function that converts an token to an IERC20 */ function toIERC20(Token token) internal pure returns (IERC20) { return IERC20(address(token)); } /** * @dev utility function that converts an token to an ERC20 */ function toERC20(Token token) internal pure returns (ERC20) { return ERC20(address(token)); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev burnable ERC20 interface */ interface IERC20Burnable { /** * @dev Destroys tokens from the caller. */ function burn(uint256 amount) external; /** * @dev Destroys tokens from a recipient, deducting from the caller's allowance * * requirements: * * - the caller must have allowance for recipient's tokens of at least the specified amount */ function burnFrom(address recipient, uint256 amount) external; } // 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; struct Fraction { uint256 n; uint256 d; } struct Fraction112 { uint112 n; uint112 d; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Fraction, Fraction112 } from "./Fraction.sol"; import { MathEx } from "./MathEx.sol"; // solhint-disable-next-line func-visibility function zeroFraction() pure returns (Fraction memory) { return Fraction({ n: 0, d: 1 }); } // solhint-disable-next-line func-visibility function zeroFraction112() pure returns (Fraction112 memory) { return Fraction112({ n: 0, d: 1 }); } /** * @dev this library provides a set of fraction operations */ library FractionLibrary { /** * @dev returns whether a standard fraction is valid */ function isValid(Fraction memory fraction) internal pure returns (bool) { return fraction.d != 0; } /** * @dev returns whether a standard fraction is positive */ function isPositive(Fraction memory fraction) internal pure returns (bool) { return isValid(fraction) && fraction.n != 0; } /** * @dev returns whether a 112-bit fraction is valid */ function isValid(Fraction112 memory fraction) internal pure returns (bool) { return fraction.d != 0; } /** * @dev returns whether a 112-bit fraction is positive */ function isPositive(Fraction112 memory fraction) internal pure returns (bool) { return isValid(fraction) && fraction.n != 0; } /** * @dev reduces a standard fraction to a 112-bit fraction */ function toFraction112(Fraction memory fraction) internal pure returns (Fraction112 memory) { Fraction memory reducedFraction = MathEx.reducedFraction(fraction, type(uint112).max); return Fraction112({ n: uint112(reducedFraction.n), d: uint112(reducedFraction.d) }); } /** * @dev expands a 112-bit fraction to a standard fraction */ function fromFraction112(Fraction112 memory fraction) internal pure returns (Fraction memory) { return Fraction({ n: fraction.n, d: fraction.d }); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { Fraction } from "./Fraction.sol"; import { PPM_RESOLUTION } from "./Constants.sol"; uint256 constant ONE = 1 << 127; struct Uint512 { uint256 hi; // 256 most significant bits uint256 lo; // 256 least significant bits } struct Sint256 { uint256 value; bool isNeg; } /** * @dev this library provides a set of complex math operations */ library MathEx { error Overflow(); /** * @dev returns `e ^ f`, where `e` is Euler's number and `f` is the input exponent: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function exp(Fraction memory f) internal pure returns (Fraction memory) { uint256 x = MathEx.mulDivF(ONE, f.n, f.d); uint256 y; uint256 z; uint256 n; if (x >= (ONE << 4)) { revert Overflow(); } unchecked { z = y = x % (ONE >> 3); // get the input modulo 2^(-3) z = (z * y) / ONE; n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / ONE; n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / ONE; n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / ONE; n += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / ONE; n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / ONE; n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / ONE; n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / ONE; n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / ONE; n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / ONE; n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / ONE; n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / ONE; n += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / ONE; n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / ONE; n += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / ONE; n += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / ONE; n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / ONE; n += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / ONE; n += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / ONE; n += z * 0x0000000000000001; // add y^20 * (20! / 20!) n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & (ONE >> 3)) != 0) n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & (ONE >> 2)) != 0) n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & (ONE >> 1)) != 0) n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & (ONE << 0)) != 0) n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & (ONE << 1)) != 0) n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & (ONE << 2)) != 0) n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & (ONE << 3)) != 0) n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) } return Fraction({ n: n, d: ONE }); } /** * @dev returns a fraction with reduced components */ function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) { uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max); return Fraction({ n: fraction.n / scale, d: fraction.d / scale }); } /** * @dev returns the weighted average of two fractions */ function weightedAverage( Fraction memory fraction1, Fraction memory fraction2, uint256 weight1, uint256 weight2 ) internal pure returns (Fraction memory) { return Fraction({ n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2, d: fraction1.d * fraction2.d * (weight1 + weight2) }); } /** * @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range * for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base` */ function isInRange( Fraction memory baseSample, Fraction memory offsetSample, uint32 maxDeviationPPM ) internal pure returns (bool) { Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM)); Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION); Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM)); return lte512(min, mid) && lte512(mid, max); } /** * @dev returns an `Sint256` positive representation of an unsigned integer */ function toPos256(uint256 n) internal pure returns (Sint256 memory) { return Sint256({ value: n, isNeg: false }); } /** * @dev returns an `Sint256` negative representation of an unsigned integer */ function toNeg256(uint256 n) internal pure returns (Sint256 memory) { return Sint256({ value: n, isNeg: true }); } /** * @dev returns the largest integer smaller than or equal to `x * y / z` */ function mulDivF( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256) { Uint512 memory xy = mul512(x, y); // if `x * y < 2 ^ 256` if (xy.hi == 0) { return xy.lo / z; } // assert `x * y / z < 2 ^ 256` if (xy.hi >= z) { revert Overflow(); } uint256 m = _mulMod(x, y, z); // `m = x * y % z` Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)` // if `n < 2 ^ 256` if (n.hi == 0) { return n.lo / z; } uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p` uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256` return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z` } /** * @dev returns the smallest integer larger than or equal to `x * y / z` */ function mulDivC( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256) { uint256 w = mulDivF(x, y, z); if (_mulMod(x, y, z) > 0) { if (w >= type(uint256).max) { revert Overflow(); } return w + 1; } return w; } /** * @dev returns the maximum of `n1 - n2` and 0 */ function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) { return n1 > n2 ? n1 - n2 : 0; } /** * @dev returns the value of `x > y` */ function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo); } /** * @dev returns the value of `x < y` */ function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo); } /** * @dev returns the value of `x >= y` */ function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return !lt512(x, y); } /** * @dev returns the value of `x <= y` */ function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) { return !gt512(x, y); } /** * @dev returns the value of `x * y` */ function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) { uint256 p = _mulModMax(x, y); uint256 q = _unsafeMul(x, y); if (p >= q) { return Uint512({ hi: p - q, lo: q }); } return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q }); } /** * @dev returns the value of `x - y`, given that `x >= y` */ function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) { if (x.lo >= y) { return Uint512({ hi: x.hi, lo: x.lo - y }); } return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) }); } /** * @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n` */ function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) { uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)` return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)` } /** * @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2` */ function _inv256(uint256 d) private pure returns (uint256) { // approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method uint256 x = 1; for (uint256 i = 0; i < 8; i++) { x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256` } return x; } /** * @dev returns `(x + y) % 2 ^ 256` */ function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return x + y; } } /** * @dev returns `(x - y) % 2 ^ 256` */ function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return x - y; } } /** * @dev returns `(x * y) % 2 ^ 256` */ function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) { unchecked { return x * y; } } /** * @dev returns `x * y % (2 ^ 256 - 1)` */ function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) { return mulmod(x, y, type(uint256).max); } /** * @dev returns `x * y % z` */ function _mulMod( uint256 x, uint256 y, uint256 z ) private pure returns (uint256) { return mulmod(x, y, z); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev this contract abstracts the block timestamp in order to allow for more flexible control in tests */ contract Time { /** * @dev returns the current time */ function _time() internal view virtual returns (uint32) { return uint32(block.timestamp); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import { IUpgradeable } from "./interfaces/IUpgradeable.sol"; import { AccessDenied } from "./Utils.sol"; /** * @dev this contract provides common utilities for upgradeable contracts */ abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable { error AlreadyInitialized(); // the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract // upgrades bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); uint32 internal constant MAX_GAP = 50; uint16 internal _initializations; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 1] private __gap; // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __Upgradeable_init() internal onlyInitializing { __AccessControl_init(); __Upgradeable_init_unchained(); } /** * @dev performs contract-specific initialization */ function __Upgradeable_init_unchained() internal onlyInitializing { _initializations = 1; // set up administrative roles _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); // allow the deployer to initially be the admin of the contract _setupRole(ROLE_ADMIN, msg.sender); } // solhint-enable func-name-mixedcase modifier onlyAdmin() { _hasRole(ROLE_ADMIN, msg.sender); _; } modifier onlyRoleMember(bytes32 role) { _hasRole(role, msg.sender); _; } function version() public view virtual override returns (uint16); /** * @dev returns the admin role */ function roleAdmin() external pure returns (bytes32) { return ROLE_ADMIN; } /** * @dev performs post-upgrade initialization * * requirements: * * - this must can be called only once per-upgrade */ function postUpgrade(bytes calldata data) external { uint16 initializations = _initializations + 1; if (initializations != version()) { revert AlreadyInitialized(); } _initializations = initializations; _postUpgrade(data); } /** * @dev an optional post-upgrade callback that can be implemented by child contracts */ function _postUpgrade( bytes calldata /* data */ ) internal virtual {} function _hasRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert AccessDenied(); } } } // 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(); } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev Owned interface */ interface IOwned { /** * @dev returns the address of the current owner */ function owner() external view returns (address); /** * @dev allows transferring the contract ownership * * requirements: * * - the caller must be the owner of the contract * - the new owner still needs to accept the transfer */ function transferOwnership(address ownerCandidate) external; /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IVersioned } from "./IVersioned.sol"; import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol"; /** * @dev this is the common interface for upgradeable contracts */ interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev an interface for a versioned contract */ interface IVersioned { function version() external view returns (uint16); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IVault } from "./IVault.sol"; interface IExternalRewardsVault is IVault {} // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol"; import { Token } from "../../token/Token.sol"; // the asset manager role is required to access all the funds bytes32 constant ROLE_ASSET_MANAGER = keccak256("ROLE_ASSET_MANAGER"); interface IVault is IUpgradeable { /** * @dev triggered when tokens have been withdrawn from the vault */ event FundsWithdrawn(Token indexed token, address indexed caller, address indexed target, uint256 amount); /** * @dev triggered when tokens have been burned from the vault */ event FundsBurned(Token indexed token, address indexed caller, uint256 amount); /** * @dev tells whether the vault accepts native token deposits */ function isPayable() external view returns (bool); /** * @dev withdraws funds held by the contract and sends them to an account */ function withdrawFunds( Token token, address payable target, uint256 amount ) external; /** * @dev burns funds held by the contract */ function burn(Token token, uint256 amount) external; }
updates program and provider's rewards/
function _snapshotRewards(ProgramData memory p, address provider) private returns (ProviderRewards storage) { Rewards storage rewards = _programRewards[p.id]; uint256 newRewardPerToken = _rewardPerToken(p, rewards); if (newRewardPerToken != rewards.rewardPerToken) { rewards.rewardPerToken = newRewardPerToken; } uint32 newUpdateTime = uint32(Math.min(_time(), p.endTime)); if (rewards.lastUpdateTime < newUpdateTime) { rewards.lastUpdateTime = newUpdateTime; } ProviderRewards storage providerRewards = _providerRewards[provider][p.id]; uint256 newPendingRewards = _pendingRewards(newRewardPerToken, providerRewards); if (newPendingRewards != 0) { providerRewards.rewardPerTokenPaid = newRewardPerToken; providerRewards.pendingRewards = newPendingRewards; } return providerRewards; }
11,787,796
pragma solidity ^0.5.16; import "./CErc20.sol"; /** * @title Compound's CErc20Immutable Contract * @notice CTokens which wrap an EIP-20 underlying and are immutable * @author Compound */ contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } } pragma solidity ^0.5.16; import "./CToken.sol"; /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CErc20 is CToken, CErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { 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 Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } }
Calculates the exchange rate from the underlying to the CToken This function does not accrue interest before calculating the exchange rate return (error code, calculated exchange rate scaled by 1e18)/ Otherwise: exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply/
function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { return (MathError.NO_ERROR, initialExchangeRateMantissa); uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } }
17,589
./full_match/80001/0x349b8C4daB2de3800f3B276CbFF9BeE6D78737B5/sources/contracts/verifiers/ForeVerifiers.sol
Changes transferability feature status Status/
function setTransferAllowance(bool status) external onlyOwner { _transfersAllowed = status; emit TransferAllowanceChanged(status); }
5,553,932
./full_match/42161/0x91808b6E8524D994AA5e47Fdb515accFF64674A2/sources/src/contracts/Core.sol
[onlyDAO] we init critical settings and variables for rebase here hgeToken_ Hedge token (interest bearing token) levToken_ Leverage token (interest bearing token) sponsorToken_ Sponsor token (normal ERC20 token) lastRebaseTime_ set the last rebase begin time. (for rebase and price update)/ 1. para checks 2. tokens 2 price and index fectch 3. finish initialization set it to true.
function initGnesisHedge( address hgeToken_, address levToken_, address sponsorToken_, uint256 lastRebaseTime_ ) public onlyDAO { require(!initialized, "HC:INITED!"); require(lastRebaseTime_ != 0, "HC: T INV"); hgeToken = IHedgeToken(hgeToken_); levToken = IHedgeToken(levToken_); sponsorToken = ISponsorToken(sponsorToken_); hgeToken.index(); levToken.index(); sponsorToken.core(); require(hedgeInfo.hedgeTokenPrice != 0, "HC:W P INV"); currSTokenIndex = index(); require(currSTokenIndex != 0, "HC:IDX INV"); lastPriceUpdateTimestamp = lastRebaseTime_; hedgeInfo.rebaseTime = lastRebaseTime_; initialized = true; }
16,307,776
//SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./BaseAsset.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Contract for Land non fungible token * @author Oleh Andrushko (https://olich.me) * @dev */ contract Land is BaseAsset { using SafeMath for uint256; uint256 private MIN_TOKEN_PRICE = 10000000000000000; // wei - 0.01 ether /** * @dev mapping from land geohash to assets geohash * @notice is one to many mapping, meaning that a single land could have more that one asset */ mapping (string => string[]) private _landAssets; /** * @dev mapping from asset geohash to a contract address (es: building geohash -> contract xxxx) * @notice is one to one mapping, meaning that for a single asset we can have only one contract address */ mapping (string => address) private _assetAddresses; constructor() public BaseAsset("VLand", "LND721") {} /** * @dev Used create a new land nft with token url metadata and unique geohash * @param to address for a receiver of newly created nft * @param _geohash geohash string * @param basePrice starting price for the nft in wei * @param _tokenURI url for token metadata */ function createLand(address to, string memory _geohash, uint256 basePrice, string memory _tokenURI) public onlyOwner returns (uint256) { require(!_geohashExists(_geohash), "Geohash was already used, the land was already created"); require(basePrice > MIN_TOKEN_PRICE, "Base price for the land should be grether than 0.01 ether"); uint256 newItemId = _generateTokenId(); _safeMint(to, newItemId); _setTokenURI(newItemId, _tokenURI); _setTokenGeohash(newItemId, _geohash); _setTokenPrice(newItemId, basePrice); return newItemId; } /** * @dev Buy a land with assets * @param _geohash target token geohash * TODO: too long and heavy function, need some refactoring here * TODO: add checks in case the caller is already a owner of one of assets */ function buyLandWithAssets(string memory _geohash) public payable { // getting total price with assets uint mainLandPrice = priceOfGeohash(_geohash); uint256 totalPrice = mainLandPrice; string[] memory assets = assetsOf(_geohash); uint256[] memory assetPrices = new uint256[](assets.length); for (uint i = 0; i < assets.length; i++) { uint256 assetPrice = BaseAsset(_assetAddresses[assets[i]]).priceOfGeohash(assets[i]); totalPrice = SafeMath.add(totalPrice, assetPrice); assetPrices[i] = assetPrice; } require(msg.value == totalPrice, "Value does not match total price of land and it assets"); // need to buy each asset throught asset contracts for (uint i = 0; i < assets.length; i++) { BaseAsset(_assetAddresses[assets[i]]).buy{ value: assetPrices[i] }(assets[i], msg.sender); } // and finally buy the main land _buy(_geohash, msg.sender, mainLandPrice); } /** * @dev Get complete price of land with assets * @param _geohash target token geohash */ function priceWithAssetsOfGeohash(string memory _geohash) public view returns (uint256) { uint256 totalPrice = priceOfGeohash(_geohash); string[] memory _assets = assetsOf(_geohash); for (uint i = 0; i < _assets.length; i++) { uint256 assetPrice = BaseAsset(_assetAddresses[_assets[i]]).priceOfGeohash(_assets[i]); totalPrice = SafeMath.add(totalPrice, assetPrice); } return totalPrice; } /** * @dev Add an asset to the land * @param _landGeohash land geohash * @param _assetGeohash asset geohash * @param _assetContractAddress the contract address of target asset geohash */ function setAsset(string memory _landGeohash, string memory _assetGeohash, address _assetContractAddress) external onlyOwner { // ensure that the asset exist on target contract require(BaseAsset(_assetContractAddress).ownerOfGeohash(_assetGeohash) != address(0), "Asset does not exist on target contract"); _setAsset(_landGeohash, _assetGeohash, _assetContractAddress); } /** * @dev Remove an asset from the land * @param _landGeohash land geohash * @param _assetGeohash asset geohash */ function removeAsset(string memory _landGeohash, string memory _assetGeohash) external onlyOwner { // ensure that land exists require(_geohashExists(_landGeohash), "Asset remove of nonexistent land"); // ensure that the asset exists require(_assetAddresses[_assetGeohash] != address(0), "Asset remove of non existing asset"); _removeLandAsset(_landGeohash, _assetGeohash); delete _assetAddresses[_assetGeohash]; } /** * @dev Remove an asset from the land array * @param _landGeohash land geohash * @param _assetGeohash asset geohash * @notice another a little bit expensive function */ function _removeLandAsset(string memory _landGeohash, string memory _assetGeohash) private { for(uint i = _indexOfAsset(_landGeohash, _assetGeohash); i < _landAssets[_landGeohash].length-1; i++){ _landAssets[_landGeohash][i] = _landAssets[_landGeohash][i+1]; } _landAssets[_landGeohash].pop(); } /** * @dev Get assets * @param _landGeohash land geohash */ function assetsOf(string memory _landGeohash) public view returns (string [] memory) { require(_geohashExists(_landGeohash), "Asset query of nonexistent land"); return _landAssets[_landGeohash]; } /** * @dev Get index of land asset in a very bad way :) * @param _landGeohash land geohash code * @param _assetGeohash target asset geohash code */ function _indexOfAsset(string memory _landGeohash, string memory _assetGeohash) private view returns (uint) { for (uint i = 0; i < _landAssets[_landGeohash].length; i++) { string memory target = _landAssets[_landGeohash][i]; if(keccak256(bytes(_assetGeohash)) == keccak256(bytes(target))) { return i; } } } /** * @dev Add an asset to the land * @param _landGeohash land geohash * @param _assetGeohash asset geohash * @param _assetContractAddress the contract address of target asset geohash */ function _setAsset(string memory _landGeohash, string memory _assetGeohash, address _assetContractAddress) private { // ensure that land exists require(_geohashExists(_landGeohash), "Asset set of nonexistent land"); // ensure that the asset has NOT been already added to some land require(_assetAddresses[_assetGeohash] == address(0), "Asset has already been added"); // add an asset to a land _landAssets[_landGeohash].push(_assetGeohash); // target contract for asset, may be needed for future uses _assetAddresses[_assetGeohash] = _assetContractAddress; } }
Add an asset to the land _landGeohash land geohash _assetGeohash asset geohash _assetContractAddress the contract address of target asset geohash/ ensure that land exists ensure that the asset has NOT been already added to some land add an asset to a land target contract for asset, may be needed for future uses
function _setAsset(string memory _landGeohash, string memory _assetGeohash, address _assetContractAddress) private { require(_geohashExists(_landGeohash), "Asset set of nonexistent land"); require(_assetAddresses[_assetGeohash] == address(0), "Asset has already been added"); _landAssets[_landGeohash].push(_assetGeohash); _assetAddresses[_assetGeohash] = _assetContractAddress; }
12,770,573
pragma solidity ^0.5; /* NOTE: @kleros/kleros-interraction is not compatible with this solc version */ /* NOTE: I put all the arbitration files in the same file because the dependancy between the different contracts is a real "headache" */ /* If someone takes up the challenge, a PR is welcome */ /** * @title CappedMath * @dev Math operations with caps for under and overflow. * NOTE: see https://raw.githubusercontent.com/kleros/kleros-interaction/master/contracts/libraries/CappedMath.sol */ library CappedMath { uint constant private UINT_MAX = 2**256 - 1; /** * @dev Adds two unsigned integers, returns 2^256 - 1 on overflow. */ function addCap(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; return c >= _a ? c : UINT_MAX; } /** * @dev Subtracts two integers, returns 0 on underflow. */ function subCap(uint _a, uint _b) internal pure returns (uint) { if (_b > _a) return 0; else return _a - _b; } /** * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow. */ function mulCap(uint _a, uint _b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring '_a' not being zero, but the // benefit is lost if '_b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) return 0; uint c = _a * _b; return c / _a == _b ? c : UINT_MAX; } } /** @title IArbitrable * Arbitrable interface. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ interface IArbitrable { /** @dev To be emmited when meta-evidence is submitted. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidence A link to the meta-evidence JSON. */ event MetaEvidence(uint indexed _metaEvidenceID, string _evidence); /** @dev To be emmited when a dispute is created to link the correct meta-evidence to the disputeID * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute. */ event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID); /** @dev To be raised when evidence are submitted. Should point to the ressource (evidences are not to be stored on chain due to gas considerations). * @param _arbitrator The arbitrator of the contract. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. * @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party. * @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json. */ event Evidence(Arbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence); /** @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) external; } /** @title Arbitrable * Arbitrable abstract contract. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ contract Arbitrable is IArbitrable { Arbitrator public arbitrator; bytes public arbitratorExtraData; // Extra data to require particular dispute and appeal behaviour. /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. */ constructor(Arbitrator _arbitrator, bytes memory _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { emit Ruling(Arbitrator(msg.sender), _disputeID, _ruling); executeRuling(_disputeID, _ruling); } /** @dev Execute a ruling of a dispute. * @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 executeRuling(uint _disputeID, uint _ruling) internal; } /** @title Arbitrator * Arbitrator abstract contract. * When developing arbitrator contracts we need to: * -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, use nbDisputes). * -Define the functions for cost display (arbitrationCost and appealCost). * -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling). */ contract Arbitrator { enum DisputeStatus {Waiting, Appealable, Solved} modifier requireArbitrationFee(bytes memory _extraData) { require(msg.value >= arbitrationCost(_extraData), "Not enough ETH to cover arbitration costs."); _; } modifier requireAppealFee(uint _disputeID, bytes memory _extraData) { require(msg.value >= appealCost(_disputeID, _extraData), "Not enough ETH to cover appeal costs."); _; } /** @dev To be raised when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when a dispute can be appealed. * @param _disputeID ID of the dispute. */ event AppealPossible(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes memory _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function arbitrationCost(bytes memory _extraData) public view returns(uint fee); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes memory _extraData) public requireAppealFee(_disputeID,_extraData) payable { emit AppealDecision(_disputeID, Arbitrable(msg.sender)); } /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint fee); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) {} /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) public view returns(uint ruling); } /** @title Centralized Arbitrator * @dev This is a centralized arbitrator deciding alone on the result of disputes. No appeals are possible. */ contract CentralizedArbitrator is Arbitrator { address public owner = msg.sender; uint arbitrationPrice; // Not public because arbitrationCost already acts as an accessor. uint constant NOT_PAYABLE_VALUE = (2**256-2)/2; // High value to be sure that the appeal is too expensive. struct DisputeStruct { Arbitrable arbitrated; uint choices; uint fee; uint ruling; DisputeStatus status; } modifier onlyOwner {require(msg.sender==owner, "Can only be called by the owner."); _;} DisputeStruct[] public disputes; /** @dev Constructor. Set the initial arbitration price. * @param _arbitrationPrice Amount to be paid for arbitration. */ constructor(uint _arbitrationPrice) public { arbitrationPrice = _arbitrationPrice; } /** @dev Set the arbitration price. Only callable by the owner. * @param _arbitrationPrice Amount to be paid for arbitration. */ function setArbitrationPrice(uint _arbitrationPrice) public onlyOwner { arbitrationPrice = _arbitrationPrice; } /** @dev Cost of arbitration. Accessor to arbitrationPrice. * @param _extraData Not used by this contract. * @return fee Amount to be paid. */ function arbitrationCost(bytes memory _extraData) public view returns(uint fee) { return arbitrationPrice; } /** @dev Cost of appeal. Since it is not possible, it's a high value which can never be paid. * @param _disputeID ID of the dispute to be appealed. Not used by this contract. * @param _extraData Not used by this contract. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint fee) { return NOT_PAYABLE_VALUE; } /** @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. When ruling ruling<=choices. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes memory _extraData) public payable returns(uint disputeID) { super.createDispute(_choices, _extraData); disputeID = disputes.push(DisputeStruct({ arbitrated: Arbitrable(msg.sender), choices: _choices, fee: msg.value, ruling: 0, status: DisputeStatus.Waiting })) - 1; // Create the dispute and return its number. emit DisputeCreation(disputeID, Arbitrable(msg.sender)); } /** @dev Give a ruling. UNTRUSTED. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision". */ function _giveRuling(uint _disputeID, uint _ruling) internal { DisputeStruct storage dispute = disputes[_disputeID]; require(_ruling <= dispute.choices, "Invalid ruling."); require(dispute.status != DisputeStatus.Solved, "The dispute must not be solved already."); dispute.ruling = _ruling; dispute.status = DisputeStatus.Solved; msg.sender.send(dispute.fee); // Avoid blocking. dispute.arbitrated.rule(_disputeID,_ruling); } /** @dev Give a ruling. UNTRUSTED. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision". */ function giveRuling(uint _disputeID, uint _ruling) public onlyOwner { return _giveRuling(_disputeID, _ruling); } /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { return disputes[_disputeID].status; } /** @dev Return the ruling of a dispute. * @param _disputeID ID of the dispute to rule. * @return ruling The ruling which would or has been given. */ function currentRuling(uint _disputeID) public view returns(uint ruling) { return disputes[_disputeID].ruling; } } /** * @title AppealableArbitrator * @dev A centralized arbitrator that can be appealed. */ contract AppealableArbitrator is CentralizedArbitrator, Arbitrable { /* Structs */ struct AppealDispute { uint rulingTime; Arbitrator arbitrator; uint appealDisputeID; } /* Storage */ uint public timeOut; mapping(uint => AppealDispute) public appealDisputes; mapping(uint => uint) public appealDisputeIDsToDisputeIDs; /* Constructor */ /** @dev Constructs the `AppealableArbitrator` contract. * @param _arbitrationPrice The amount to be paid for arbitration. * @param _arbitrator The back up arbitrator. * @param _arbitratorExtraData Not used by this contract. * @param _timeOut The time out for the appeal period. */ constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut ) public CentralizedArbitrator(_arbitrationPrice) Arbitrable(_arbitrator, _arbitratorExtraData) { timeOut = _timeOut; } /* External */ /** @dev Changes the back up arbitrator. * @param _arbitrator The new back up arbitrator. */ function changeArbitrator(Arbitrator _arbitrator) external onlyOwner { arbitrator = _arbitrator; } /** @dev Changes the time out. * @param _timeOut The new time out. */ function changeTimeOut(uint _timeOut) external onlyOwner { timeOut = _timeOut; } /* External Views */ /** @dev Gets the specified dispute's latest appeal ID. * @param _disputeID The ID of the dispute. */ function getAppealDisputeID(uint _disputeID) external view returns(uint disputeID) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) disputeID = AppealableArbitrator(address(appealDisputes[_disputeID].arbitrator)).getAppealDisputeID(appealDisputes[_disputeID].appealDisputeID); else disputeID = _disputeID; } /* Public */ /** @dev Appeals a ruling. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. */ function appeal(uint _disputeID, bytes memory _extraData) public payable requireAppealFee(_disputeID, _extraData) { super.appeal(_disputeID, _extraData); if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) appealDisputes[_disputeID].arbitrator.appeal.value(msg.value)(appealDisputes[_disputeID].appealDisputeID, _extraData); else { appealDisputes[_disputeID].arbitrator = arbitrator; appealDisputes[_disputeID].appealDisputeID = arbitrator.createDispute.value(msg.value)(disputes[_disputeID].choices, _extraData); appealDisputeIDsToDisputeIDs[appealDisputes[_disputeID].appealDisputeID] = _disputeID; } } /** @dev Gives a ruling. * @param _disputeID The ID of the dispute. * @param _ruling The ruling. */ function giveRuling(uint _disputeID, uint _ruling) public { require(disputes[_disputeID].status != DisputeStatus.Solved, "The specified dispute is already resolved."); if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) { require(Arbitrator(msg.sender) == appealDisputes[_disputeID].arbitrator, "Appealed disputes must be ruled by their back up arbitrator."); super._giveRuling(_disputeID, _ruling); } else { require(msg.sender == owner, "Not appealed disputes must be ruled by the owner."); if (disputes[_disputeID].status == DisputeStatus.Appealable) { if (now - appealDisputes[_disputeID].rulingTime > timeOut) super._giveRuling(_disputeID, disputes[_disputeID].ruling); else revert("Time out time has not passed yet."); } else { disputes[_disputeID].ruling = _ruling; disputes[_disputeID].status = DisputeStatus.Appealable; appealDisputes[_disputeID].rulingTime = now; emit AppealPossible(_disputeID, disputes[_disputeID].arbitrated); } } } /* Public Views */ /** @dev Gets the cost of appeal for the specified dispute. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. * @return The cost of the appeal. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint cost) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) cost = appealDisputes[_disputeID].arbitrator.appealCost(appealDisputes[_disputeID].appealDisputeID, _extraData); else if (disputes[_disputeID].status == DisputeStatus.Appealable) cost = arbitrator.arbitrationCost(_extraData); else cost = NOT_PAYABLE_VALUE; } /** @dev Gets the status of the specified dispute. * @param _disputeID The ID of the dispute. * @return The status. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) status = appealDisputes[_disputeID].arbitrator.disputeStatus(appealDisputes[_disputeID].appealDisputeID); else status = disputes[_disputeID].status; } /** @dev Return the ruling of a dispute. * @param _disputeID ID of the dispute to rule. * @return ruling The ruling which would or has been given. */ function currentRuling(uint _disputeID) public view returns(uint ruling) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) // Appealed. ruling = appealDisputes[_disputeID].arbitrator.currentRuling(appealDisputes[_disputeID].appealDisputeID); // Retrieve ruling from the arbitrator whom the dispute is appealed to. else ruling = disputes[_disputeID].ruling; // Not appealed, basic case. } /* Internal */ /** @dev Executes the ruling of the specified dispute. * @param _disputeID The ID of the dispute. * @param _ruling The ruling. */ function executeRuling(uint _disputeID, uint _ruling) internal { require( appealDisputes[appealDisputeIDsToDisputeIDs[_disputeID]].arbitrator != Arbitrator(address(0)), "The dispute must have been appealed." ); giveRuling(appealDisputeIDsToDisputeIDs[_disputeID], _ruling); } } /** * @title EnhancedAppealableArbitrator * @author Enrique Piqueras - <[email protected]> * @dev Implementation of `AppealableArbitrator` that supports `appealPeriod`. */ contract EnhancedAppealableArbitrator is AppealableArbitrator { /* Constructor */ /** @dev Constructs the `EnhancedAppealableArbitrator` contract. * @param _arbitrationPrice The amount to be paid for arbitration. * @param _arbitrator The back up arbitrator. * @param _arbitratorExtraData Not used by this contract. * @param _timeOut The time out for the appeal period. */ constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut ) public AppealableArbitrator(_arbitrationPrice, _arbitrator, _arbitratorExtraData, _timeOut) {} /* Public Views */ /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) (start, end) = appealDisputes[_disputeID].arbitrator.appealPeriod(appealDisputes[_disputeID].appealDisputeID); else { start = appealDisputes[_disputeID].rulingTime; require(start != 0, "The specified dispute is not appealable."); end = start + timeOut; } } } /** * @title Permission Interface * This is a permission interface for arbitrary values. The values can be cast to the required types. */ interface PermissionInterface { /** * @dev Return true if the value is allowed. * @param _value The value we want to check. * @return allowed True if the value is allowed, false otherwise. */ function isPermitted(bytes32 _value) external view returns (bool allowed); } /** * @title ArbitrableBetList * This smart contract is a viewer moderation for the bet goal contract. * This is working progress. */ contract ArbitrableBetList is IArbitrable { using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1. /* Enums */ enum BetStatus { Absent, // The bet is not in the registry. Registered, // The bet is in the registry. RegistrationRequested, // The bet has a request to be added to the registry. ClearingRequested // The bet has a request to be removed from the registry. } enum Party { None, // Party per default when there is no challenger or requester. Also used for unconclusive ruling. Requester, // Party that made the request to change a bet status. Challenger // Party that challenges the request to change a bet status. } // ************************ // // * Request Life Cycle * // // ************************ // // Changes to the bet status are made via requests for either listing or removing a bet from the Bet Curated Registry. // To make or challenge a request, a party must pay a deposit. This value will be rewarded to the party that ultimately wins a dispute. If no one challenges the request, the value will be reimbursed to the requester. // Additionally to the challenge reward, in the case a party challenges a request, both sides must fully pay the amount of arbitration fees required to raise a dispute. The party that ultimately wins the case will be reimbursed. // Finally, arbitration fees can be crowdsourced. To incentivise insurers, an additional fee stake must be deposited. Contributors that fund the side that ultimately wins a dispute will be reimbursed and rewarded with the other side's fee stake proportionally to their contribution. // In summary, costs for placing or challenging a request are the following: // - A challenge reward given to the party that wins a potential dispute. // - Arbitration fees used to pay jurors. // - A fee stake that is distributed among insurers of the side that ultimately wins a dispute. /* Structs */ struct Bet { BetStatus status; // The status of the bet. Request[] requests; // List of status change requests made for the bet. } // Some arrays below have 3 elements to map with the Party enums for better readability: // - 0: is unused, matches `Party.None`. // - 1: for `Party.Requester`. // - 2: for `Party.Challenger`. struct Request { bool disputed; // True if a dispute was raised. uint disputeID; // ID of the dispute, if any. uint submissionTime; // Time when the request was made. Used to track when the challenge period ends. bool resolved; // True if the request was executed and/or any disputes raised were resolved. address[3] parties; // Address of requester and challenger, if any. Round[] rounds; // Tracks each round of a dispute. Party ruling; // The final ruling given, if any. Arbitrator arbitrator; // The arbitrator trusted to solve disputes for this request. bytes arbitratorExtraData; // The extra data for the trusted arbitrator of this request. } struct Round { uint[3] paidFees; // Tracks the fees paid by each side on this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint 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 => uint[3]) contributions; // Maps contributors to their contributions for each side. } /* Storage */ // Constants uint RULING_OPTIONS = 2; // The amount of non 0 choices the arbitrator can give. // Settings address public governor; // The address that can make governance changes to the parameters of the Bet Curated Registry. Arbitrator arbitrator; bytes public arbitratorExtraData; address public selfCommitmentRegistry; // The address of the selfCommitmentRegistry contract. uint public requesterBaseDeposit; // The base deposit to make a request. uint public challengerBaseDeposit; // The base deposit to challenge a request. uint public challengePeriodDuration; // The time before a request becomes executable if not challenged. uint public metaEvidenceUpdates; // The number of times the meta evidence has been updated. Used to track the latest meta evidence ID. // The required fee stake that a party must pay depends on who won the previous round and is proportional to the arbitration cost such that the fee stake for a round is stake multiplier * arbitration cost for that round. // Multipliers are in basis points. uint public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round. uint public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round. uint public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where there isn't a winner and loser (e.g. when it's the first round or the arbitrator ruled "refused to rule"/"could not rule"). uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. // Registry data. mapping(uint => Bet) public bets; // Maps the uint bet to the bet data. mapping(address => mapping(uint => uint)) public arbitratorDisputeIDToBetID; // Maps a dispute ID to the bet with the disputed request. uint[] public betList; // List of submitted bets. /* Modifiers */ modifier onlyGovernor {require(msg.sender == governor, "The caller must be the governor."); _;} /* Events */ /** * @dev Emitted when a party submits a new bet. * @param _betID The bet. * @param _requester The address of the party that made the request. */ event BetSubmitted(uint indexed _betID, address indexed _requester); /** @dev Emitted when a party makes a request to change a bet status. * @param _betID The bet index. * @param _registrationRequest Whether the request is a registration request. False means it is a clearing request. */ event RequestSubmitted(uint indexed _betID, bool _registrationRequest); /** * @dev Emitted when a party makes a request, dispute or appeals are raised, or when a request is resolved. * @param _requester Address of the party that submitted the request. * @param _challenger Address of the party that has challenged the request, if any. * @param _betID The address. * @param _status The status of the bet. * @param _disputed Whether the bet is disputed. * @param _appealed Whether the current round was appealed. */ event BetStatusChange( address indexed _requester, address indexed _challenger, uint indexed _betID, BetStatus _status, bool _disputed, bool _appealed ); /** @dev Emitted when a reimbursements and/or contribution rewards are withdrawn. * @param _betID The bet ID from which the withdrawal was made. * @param _contributor The address that sent the contribution. * @param _request The request from which the withdrawal was made. * @param _round The round from which the reward was taken. * @param _value The value of the reward. */ event RewardWithdrawal(uint indexed _betID, address indexed _contributor, uint indexed _request, uint _round, uint _value); /* Constructor */ /** * @dev Constructs the arbitrable token curated registry. * @param _arbitrator The trusted arbitrator to resolve potential disputes. * @param _arbitratorExtraData Extra data for the trusted arbitrator contract. * @param _registrationMetaEvidence The URI of the meta evidence object for registration requests. * @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests. * @param _governor The trusted governor of this contract. * @param _requesterBaseDeposit The base deposit to make a request. * @param _challengerBaseDeposit The base deposit to challenge a request. * @param _challengePeriodDuration The time in seconds, parties have to challenge a request. * @param _sharedStakeMultiplier Multiplier of the arbitration cost that each party must pay as fee stake for a round when there isn't a winner/loser in the previous round (e.g. when it's the first round or the arbitrator refused to or did not rule). In basis points. * @param _winnerStakeMultiplier Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. * @param _loserStakeMultiplier Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. */ constructor( Arbitrator _arbitrator, bytes memory _arbitratorExtraData, string memory _registrationMetaEvidence, string memory _clearingMetaEvidence, address _governor, uint _requesterBaseDeposit, uint _challengerBaseDeposit, uint _challengePeriodDuration, uint _sharedStakeMultiplier, uint _winnerStakeMultiplier, uint _loserStakeMultiplier ) public { emit MetaEvidence(0, _registrationMetaEvidence); emit MetaEvidence(1, _clearingMetaEvidence); governor = _governor; arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; requesterBaseDeposit = _requesterBaseDeposit; challengerBaseDeposit = _challengerBaseDeposit; challengePeriodDuration = _challengePeriodDuration; sharedStakeMultiplier = _sharedStakeMultiplier; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; } /* External and Public */ // ************************ // // * Requests * // // ************************ // /** @dev Submits a request to change an address status. Accepts enough ETH to fund a potential dispute considering the current required amount and reimburses the rest. TRUSTED. * @param _betID The address. * @param _sender The address of the sender. */ function requestStatusChange(uint _betID, address payable _sender) external payable { Bet storage bet = bets[_betID]; if (bet.requests.length == 0) { // Initial bet registration. require(msg.sender == selfCommitmentRegistry); betList.push(_betID); emit BetSubmitted(_betID, _sender); } // Update bet status. if (bet.status == BetStatus.Absent) bet.status = BetStatus.RegistrationRequested; else if (bet.status == BetStatus.Registered) bet.status = BetStatus.ClearingRequested; else revert("Bet already has a pending request."); // Setup request. Request storage request = bet.requests[bet.requests.length++]; request.parties[uint(Party.Requester)] = _sender; request.submissionTime = now; request.arbitrator = arbitrator; request.arbitratorExtraData = arbitratorExtraData; Round storage round = request.rounds[request.rounds.length++]; emit RequestSubmitted(_betID, bet.status == BetStatus.RegistrationRequested); // Amount required to fully the requester: requesterBaseDeposit + arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = request.arbitrator.arbitrationCost(request.arbitratorExtraData); uint totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(requesterBaseDeposit); contribute(round, Party.Requester, _sender, msg.value, totalCost); require(round.paidFees[uint(Party.Requester)] >= totalCost, "You must fully fund your side."); round.hasPaid[uint(Party.Requester)] = true; emit BetStatusChange( request.parties[uint(Party.Requester)], address(0x0), _betID, bet.status, false, false ); } /** @dev Get the total cost */ function getTotalCost() external view returns (uint totalCost) { uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(requesterBaseDeposit); } /** @dev Challenges the latest request of a bet. Accepts enough ETH to fund a potential dispute considering the current required amount. Reimburses unused ETH. TRUSTED. * @param _betID The bet ID with the request to challenge. * @param _evidence A link to an evidence using its URI. Ignored if not provided or if not enough funds were provided to create a dispute. */ function challengeRequest(uint _betID, string calldata _evidence) external payable { Bet storage bet = bets[_betID]; require( bet.status == BetStatus.RegistrationRequested || bet.status == BetStatus.ClearingRequested, "The bet must have a pending request." ); Request storage request = bet.requests[bet.requests.length - 1]; require(now - request.submissionTime <= challengePeriodDuration, "Challenges must occur during the challenge period."); require(!request.disputed, "The request should not have already been disputed."); // Take the deposit and save the challenger's bet. request.parties[uint(Party.Challenger)] = msg.sender; Round storage round = request.rounds[request.rounds.length - 1]; uint arbitrationCost = request.arbitrator.arbitrationCost(request.arbitratorExtraData); uint totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(challengerBaseDeposit); contribute(round, Party.Challenger, msg.sender, msg.value, totalCost); require(round.paidFees[uint(Party.Challenger)] >= totalCost, "You must fully fund your side."); round.hasPaid[uint(Party.Challenger)] = true; // Raise a dispute. request.disputeID = request.arbitrator.createDispute.value(arbitrationCost)(RULING_OPTIONS, request.arbitratorExtraData); arbitratorDisputeIDToBetID[address(request.arbitrator)][request.disputeID] = _betID; request.disputed = true; request.rounds.length++; round.feeRewards = round.feeRewards.subCap(arbitrationCost); emit Dispute( request.arbitrator, request.disputeID, bet.status == BetStatus.RegistrationRequested ? 2 * metaEvidenceUpdates : 2 * metaEvidenceUpdates + 1, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))) ); emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], _betID, bet.status, true, false ); if (bytes(_evidence).length > 0) emit Evidence(request.arbitrator, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))), msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. TRUSTED. * @param _betID The bet index. * @param _side The recipient of the contribution. */ function fundAppeal(uint _betID, Party _side) external payable { // Recipient must be either the requester or challenger. require(_side == Party.Requester || _side == Party.Challenger); // solium-disable-line error-reason Bet storage bet = bets[_betID]; require( bet.status == BetStatus.RegistrationRequested || bet.status == BetStatus.ClearingRequested, "The bet must have a pending request." ); Request storage request = bet.requests[bet.requests.length - 1]; require(request.disputed, "A dispute must have been raised to fund an appeal."); (uint appealPeriodStart, uint appealPeriodEnd) = request.arbitrator.appealPeriod(request.disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Contributions must be made within the appeal period." ); // Amount required to fully fund each side: arbitration cost + (arbitration cost * multiplier) Round storage round = request.rounds[request.rounds.length - 1]; Party winner = Party(request.arbitrator.currentRuling(request.disputeID)); Party loser; if (winner == Party.Requester) loser = Party.Challenger; else if (winner == Party.Challenger) loser = Party.Requester; require(!(_side==loser) || (now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2), "The loser must contribute during the first half of the appeal period."); uint multiplier; if (_side == winner) multiplier = winnerStakeMultiplier; else if (_side == loser) multiplier = loserStakeMultiplier; else multiplier = sharedStakeMultiplier; uint appealCost = request.arbitrator.appealCost(request.disputeID, request.arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); contribute(round, _side, msg.sender, msg.value, totalCost); if (round.paidFees[uint(_side)] >= totalCost) round.hasPaid[uint(_side)] = true; // Raise appeal if both sides are fully funded. if (round.hasPaid[uint(Party.Challenger)] && round.hasPaid[uint(Party.Requester)]) { request.arbitrator.appeal.value(appealCost)(request.disputeID, request.arbitratorExtraData); request.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], _betID, bet.status, true, true ); } } /** @dev Reimburses contributions if no disputes were raised. If a dispute was raised, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * @param _beneficiary The address that made contributions to a request. * @param _betID The bet index submission with the request from which to withdraw. * @param _request The request from which to withdraw. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards(address payable _beneficiary, uint _betID, uint _request, uint _round) public { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; Round storage round = request.rounds[_round]; // The request must be executed and there can be no disputes pending resolution. require(request.resolved); // solium-disable-line error-reason uint reward; if (!round.hasPaid[uint(Party.Requester)] || !round.hasPaid[uint(Party.Challenger)]) { // Reimburse if not enough fees were raised to appeal the ruling. reward = round.contributions[_beneficiary][uint(Party.Requester)] + round.contributions[_beneficiary][uint(Party.Challenger)]; round.contributions[_beneficiary][uint(Party.Requester)] = 0; round.contributions[_beneficiary][uint(Party.Challenger)] = 0; } else if (request.ruling == Party.None) { // No disputes were raised, or there isn't a winner and loser. Reimburse unspent fees proportionally. uint rewardRequester = round.paidFees[uint(Party.Requester)] > 0 ? (round.contributions[_beneficiary][uint(Party.Requester)] * round.feeRewards) / (round.paidFees[uint(Party.Challenger)] + round.paidFees[uint(Party.Requester)]) : 0; uint rewardChallenger = round.paidFees[uint(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint(Party.Challenger)] + round.paidFees[uint(Party.Requester)]) : 0; reward = rewardRequester + rewardChallenger; round.contributions[_beneficiary][uint(Party.Requester)] = 0; round.contributions[_beneficiary][uint(Party.Challenger)] = 0; } else { // Reward the winner. reward = round.paidFees[uint(request.ruling)] > 0 ? (round.contributions[_beneficiary][uint(request.ruling)] * round.feeRewards) / round.paidFees[uint(request.ruling)] : 0; round.contributions[_beneficiary][uint(request.ruling)] = 0; } emit RewardWithdrawal(_betID, _beneficiary, _request, _round, reward); _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Withdraws rewards and reimbursements of multiple rounds at once. This function is O(n) where n is the number of rounds. This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions to the request. * @param _betID The bet index. * @param _request The request from which to withdraw contributions. * @param _cursor The round from where to start withdrawing. * @param _count Rounds greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of rounds, iterates until the last round. */ function batchRoundWithdraw(address payable _beneficiary, uint _betID, uint _request, uint _cursor, uint _count) public { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; for (uint i = _cursor; i<request.rounds.length && (_count==0 || i<_count); i++) withdrawFeesAndRewards(_beneficiary, _betID, _request, i); } /** @dev Withdraws rewards and reimbursements of multiple requests at once. This function is O(n*m) where n is the number of requests and m is the number of rounds. This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions to the request. * @param _betID The bet index. * @param _cursor The request from which to start withdrawing. * @param _count Requests greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of request, iterates until the last request. * @param _roundCursor The round of each request from where to start withdrawing. * @param _roundCount Rounds greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of rounds a request has, iteration for that request will stop at the last round. */ function batchRequestWithdraw( address payable _beneficiary, uint _betID, uint _cursor, uint _count, uint _roundCursor, uint _roundCount ) external { Bet storage bet = bets[_betID]; for (uint i = _cursor; i<bet.requests.length && (_count==0 || i<_count); i++) batchRoundWithdraw(_beneficiary, _betID, i, _roundCursor, _roundCount); } /** @dev Executes a request if the challenge period passed and no one challenged the request. * @param _betID The bet index with the request to execute. */ function executeRequest(uint _betID) external { Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; require( now - request.submissionTime > challengePeriodDuration, "Time to challenge the request must have passed." ); require(!request.disputed, "The request should not be disputed."); if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Registered; else if (bet.status == BetStatus.ClearingRequested) bet.status = BetStatus.Absent; else revert("There must be a request."); request.resolved = true; address payable party = address(uint160(request.parties[uint(Party.Requester)])); withdrawFeesAndRewards(party, _betID, bet.requests.length - 1, 0); // Automatically withdraw for the requester. emit BetStatusChange( request.parties[uint(Party.Requester)], address(0x0), _betID, bet.status, false, false ); } /** @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED. * Overrides parent function to account for the situation where the winner loses a case due to paying less appeal fees than expected. * @param _disputeID ID of the dispute in the arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { Party resultRuling = Party(_ruling); uint _betID = arbitratorDisputeIDToBetID[msg.sender][_disputeID]; Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; Round storage round = request.rounds[request.rounds.length - 1]; require(_ruling <= RULING_OPTIONS); // solium-disable-line error-reason require(address(request.arbitrator) == msg.sender); // solium-disable-line error-reason require(!request.resolved); // solium-disable-line error-reason // The ruling is inverted if the loser paid its fees. if (round.hasPaid[uint(Party.Requester)] == true) // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created. resultRuling = Party.Requester; else if (round.hasPaid[uint(Party.Challenger)] == true) resultRuling = Party.Challenger; emit Ruling(Arbitrator(msg.sender), _disputeID, uint(resultRuling)); executeRuling(_disputeID, uint(resultRuling)); } /** @dev Submit a reference to evidence. EVENT. * @param _betID The bet index. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(uint _betID, string calldata _evidence) external { Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; require(!request.resolved, "The dispute must not already be resolved."); emit Evidence(request.arbitrator, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))), msg.sender, _evidence); } // ************************ // // * Governance * // // ************************ // /** @dev Change the duration of the challenge period. * @param _challengePeriodDuration The new duration of the challenge period. */ function changeTimeToChallenge(uint _challengePeriodDuration) external onlyGovernor { challengePeriodDuration = _challengePeriodDuration; } /** @dev Change the base amount required as a deposit to make a request. * @param _requesterBaseDeposit The new base amount of wei required to make a request. */ function changeRequesterBaseDeposit(uint _requesterBaseDeposit) external onlyGovernor { requesterBaseDeposit = _requesterBaseDeposit; } /** @dev Change the base amount required as a deposit to challenge a request. * @param _challengerBaseDeposit The new base amount of wei required to challenge a request. */ function changeChallengerBaseDeposit(uint _challengerBaseDeposit) external onlyGovernor { challengerBaseDeposit = _challengerBaseDeposit; } /** @dev Change the governor of the token curated registry. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** @dev Change the address of the goal bet registry contract. * @param _selfCommitmentRegistry The address of the new goal bet registry contract. */ function changeSelfCommitmentRegistry(address _selfCommitmentRegistry) external onlyGovernor { selfCommitmentRegistry = _selfCommitmentRegistry; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by parties when there isn't a winner or loser. * @param _sharedStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeSharedStakeMultiplier(uint _sharedStakeMultiplier) external onlyGovernor { sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by the winner of the previous round. * @param _winnerStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeWinnerStakeMultiplier(uint _winnerStakeMultiplier) external onlyGovernor { winnerStakeMultiplier = _winnerStakeMultiplier; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by the party that lost the previous round. * @param _loserStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeLoserStakeMultiplier(uint _loserStakeMultiplier) external onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; } /** @dev Change the arbitrator to be used for disputes that may be raised in the next requests. The arbitrator is trusted to support appeal periods and not reenter. * @param _arbitrator The new trusted arbitrator to be used in the next requests. * @param _arbitratorExtraData The extra data used by the new arbitrator. */ function changeArbitrator(Arbitrator _arbitrator, bytes calldata _arbitratorExtraData) external onlyGovernor { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Update the meta evidence used for disputes. * @param _registrationMetaEvidence The meta evidence to be used for future registration request disputes. * @param _clearingMetaEvidence The meta evidence to be used for future clearing request disputes. */ function changeMetaEvidence(string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence) external onlyGovernor { metaEvidenceUpdates++; emit MetaEvidence(2 * metaEvidenceUpdates, _registrationMetaEvidence); emit MetaEvidence(2 * metaEvidenceUpdates + 1, _clearingMetaEvidence); } /* Internal */ /** @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(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Make a fee contribution. * @param _round The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. */ function contribute(Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired) internal { // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)])); _round.contributions[_contributor][uint(_side)] += contribution; _round.paidFees[uint(_side)] += contribution; _round.feeRewards += contribution; // Reimburse leftover ETH. _contributor.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. } /** @dev Execute the ruling of a dispute. * @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 executeRuling(uint _disputeID, uint _ruling) internal { uint betID = arbitratorDisputeIDToBetID[msg.sender][_disputeID]; Bet storage bet = bets[betID]; Request storage request = bet.requests[bet.requests.length - 1]; Party winner = Party(_ruling); // Update bet state if (winner == Party.Requester) { // Execute Request if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Registered; else bet.status = BetStatus.Absent; } else { // Revert to previous state. if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Absent; else if (bet.status == BetStatus.ClearingRequested) bet.status = BetStatus.Registered; } request.resolved = true; request.ruling = Party(_ruling); // Automatically withdraw. if (winner == Party.None) { address payable requester = address(uint160(request.parties[uint(Party.Requester)])); address payable challenger = address(uint160(request.parties[uint(Party.Challenger)])); withdrawFeesAndRewards(requester, betID, bet.requests.length-1, 0); withdrawFeesAndRewards(challenger, betID, bet.requests.length-1, 0); } else { address payable winnerAddr = address(uint160(request.parties[uint(winner)])); withdrawFeesAndRewards(winnerAddr, betID, bet.requests.length-1, 0); } emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], betID, bet.status, request.disputed, false ); } /* Views */ /** @dev Return true if the bet is on the list. * @param _betID The bet index. * @return allowed True if the address is allowed, false otherwise. */ function isPermitted(uint _betID) external view returns (bool allowed) { Bet storage bet = bets[_betID]; return bet.status == BetStatus.Registered || bet.status == BetStatus.ClearingRequested; } /* Interface Views */ /** @dev Return the sum of withdrawable wei of a request an account is entitled to. This function is O(n), where n is the number of rounds of the request. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _betID The bet index to query. * @param _beneficiary The contributor for which to query. * @param _request The request from which to query for. * @return The total amount of wei available to withdraw. */ function amountWithdrawable(uint _betID, address _beneficiary, uint _request) external view returns (uint total){ Request storage request = bets[_betID].requests[_request]; if (!request.resolved) return total; for (uint i = 0; i < request.rounds.length; i++) { Round storage round = request.rounds[i]; if (!request.disputed || request.ruling == Party.None) { uint rewardRequester = round.paidFees[uint(Party.Requester)] > 0 ? (round.contributions[_beneficiary][uint(Party.Requester)] * round.feeRewards) / (round.paidFees[uint(Party.Requester)] + round.paidFees[uint(Party.Challenger)]) : 0; uint rewardChallenger = round.paidFees[uint(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint(Party.Requester)] + round.paidFees[uint(Party.Challenger)]) : 0; total += rewardRequester + rewardChallenger; } else { total += round.paidFees[uint(request.ruling)] > 0 ? (round.contributions[_beneficiary][uint(request.ruling)] * round.feeRewards) / round.paidFees[uint(request.ruling)] : 0; } } return total; } /** @dev Return the numbers of bets that were submitted. Includes bets that never made it to the list or were later removed. * @return count The numbers of bets in the list. */ function betCount() external view returns (uint count) { return betList.length; } /** @dev Gets the contributions made by a party for a given round of a request. * @param _betID The bet index. * @param _request The position of the request. * @param _round The position of the round. * @param _contributor The address of the contributor. * @return The contributions. */ function getContributions( uint _betID, uint _request, uint _round, address _contributor ) external view returns(uint[3] memory contributions) { Request storage request = bets[_betID].requests[_request]; Round storage round = request.rounds[_round]; contributions = round.contributions[_contributor]; } /** @dev Returns bet information. Includes length of requests array. * @param _betID The queried bet index. * @return The bet information. */ function getBetInfo(uint _betID) external view returns ( BetStatus status, uint numberOfRequests ) { Bet storage bet = bets[_betID]; return ( bet.status, bet.requests.length ); } /** @dev Gets information on a request made for a bet. * @param _betID The queried bet index. * @param _request The request to be queried. * @return The request information. */ function getRequestInfo(uint _betID, uint _request) external view returns ( bool disputed, uint disputeID, uint submissionTime, bool resolved, address[3] memory parties, uint numberOfRounds, Party ruling, Arbitrator arbitratorRequest, bytes memory arbitratorExtraData ) { Request storage request = bets[_betID].requests[_request]; return ( request.disputed, request.disputeID, request.submissionTime, request.resolved, request.parties, request.rounds.length, request.ruling, request.arbitrator, request.arbitratorExtraData ); } /** @dev Gets the information on a round of a request. * @param _betID The queried bet index. * @param _request The request to be queried. * @param _round The round to be queried. * @return The round information. */ function getRoundInfo(uint _betID, uint _request, uint _round) external view returns ( bool appealed, uint[3] memory paidFees, bool[3] memory hasPaid, uint feeRewards ) { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; Round storage round = request.rounds[_round]; return ( _round != (request.rounds.length-1), round.paidFees, round.hasPaid, round.feeRewards ); } } contract SelfCommitment is IArbitrable { using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1. // **************************** // // * Contract variables * // // **************************** // struct Bet { string description; // alias metaevidence uint[3] period; // endBetPeriod, startClaimPeriod, endClaimPeriod uint[2] ratio; // For irrational numbers we assume that the loss of wei is negligible address[3] parties; uint[2] amount; // betterAmount (max), takerTotalAmount mapping(address => uint) amountTaker; bool isPrivate; mapping(address => bool) allowAddress; Arbitrator arbitrator; bytes arbitratorExtraData; uint[3] stakeMultiplier; Status status; // Status of the claim relative to a dispute. uint disputeID; // If dispute exists, the ID of the dispute. Round[] rounds; // Tracks each round of a dispute. Party ruling; // The final ruling given, if any. } struct Round { uint[3] paidFees; // Tracks the fees paid by each side on this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint 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 => uint[3]) contributions; // Maps contributors to their contributions for each side. } Bet[] public bets; // Amount of choices to solve the dispute if needed. uint8 constant AMOUNT_OF_CHOICES = 2; // Enum relative to different periods in the case of a negotiation or dispute. enum Status {NoDispute, WaitingAsker, WaitingTaker, DisputeCreated, Resolved} // The different parties of the dispute. enum Party {None, Asker, Taker} // The different ruling for the dispute resolution. enum RulingOptions {NoRuling, AskerWins, TakerWins} // One-to-one relationship between the dispute and the bet. mapping(address => mapping(uint => uint)) public arbitratorDisputeIDtoBetID; // Settings address public governor; // The address that can make governance changes to the parameters. address public betArbitrableList; uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. // **************************** // // * Modifier * // // **************************** // modifier onlyGovernor {require(msg.sender == address(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 _transactionID The index of the transaction. * @param _party The party who has to pay. */ event HasToPayFee(uint indexed _transactionID, Party _party); /** @dev To be emitted when a party get the rewards or the deposit. * @param _id The index of the bet. * @param _party The party that paid. * @param _amount The amount paid. */ event Reward(uint indexed _id, Party _party, uint _amount); /** @dev Emitted when a reimbursements and/or contribution rewards are withdrawn. * @param _id The ID of the bet. * @param _contributor The address that sent the contribution. * @param _round The round from which the reward was taken. * @param _value The value of the reward. */ event RewardWithdrawal(uint indexed _id, address indexed _contributor, uint _round, uint _value); /* Constructor */ /** * @dev Constructs the arbitrable token curated registry. * @param _governor The trusted governor of this contract. */ constructor( address _governor ) public { governor = _governor; } // **************************** // // * Contract functions * // // * Modifying the state * // // **************************** // /** @dev To add a new bet. UNTRUSTED. * @param _description The description of the bet. * @param _period The different periods of the bet. * @param _ratio The ratio of the bet. * @param _allowAddress Addresses who are allowed to bet. Empty for all addresses. * @param _arbitrator The arbitrator of the bet. * @param _arbitratorExtraData The configuration for the arbitration. * @param _stakeMultiplier The multipler of the deposit for the different parties. */ function ask( string calldata _description, uint[3] calldata _period, uint[2] calldata _ratio, address[] calldata _allowAddress, Arbitrator _arbitrator, bytes calldata _arbitratorExtraData, uint[3] calldata _stakeMultiplier ) external payable { ArbitrableBetList betArbitrableListInstance = ArbitrableBetList(betArbitrableList); uint totalCost = betArbitrableListInstance.getTotalCost(); require(msg.value > totalCost); require(msg.value - totalCost >= 10000); require(_ratio[0] > 1); require(_ratio[0] > _ratio[1]); require(_period[0] > now); uint amountXratio1 = msg.value * _ratio[0]; // _ratio0 > (_ratio0/_ratio1) require(amountXratio1/msg.value == _ratio[0]); // To prevent multiply overflow. betArbitrableListInstance.requestStatusChange.value(totalCost)(bets.length, msg.sender); Bet storage bet = bets[bets.length++]; bet.parties[1] = msg.sender; bet.description = _description; bet.period = _period; bet.ratio = _ratio; bet.amount = [msg.value - totalCost, 0]; if (_allowAddress.length > 0) { for(uint i; i < _allowAddress.length; i++) bet.allowAddress[_allowAddress[i]] = true; bet.isPrivate = true; } bet.arbitrator = _arbitrator; bet.arbitratorExtraData = _arbitratorExtraData; bet.stakeMultiplier = _stakeMultiplier; } /** @dev To accept a bet. UNTRUSTED. * @param _id The id of the bet. */ function take( uint _id ) external payable { require(msg.value > 0); Bet storage bet = bets[_id]; require(now < bet.period[0], "Should bet before the end period bet."); require(bet.amount[0] > bet.amount[1]); if (bet.isPrivate) require(bet.allowAddress[msg.sender]); address payable taker = msg.sender; // r = bet.ratio[0] / bet.ratio[1] // maxAmountToBet = x / (r-1) - y // maxAmountToBet = x*x / (rx-x) - y uint maxAmountToBet = bet.amount[0]*bet.amount[0] / (bet.ratio[0]*bet.amount[0]/bet.ratio[1] - bet.amount[0]) - bet.amount[1]; uint amountBet = msg.value <= maxAmountToBet ? msg.value : maxAmountToBet; bet.amount[1] += amountBet; bet.amountTaker[taker] = amountBet; if (msg.value > maxAmountToBet) taker.transfer(msg.value - maxAmountToBet); } /** @dev Withdraw the bet if no one took it. TRUSTED. * @param _id The id of the bet. */ function withdraw( uint _id ) external { Bet storage bet = bets[_id]; require(now > bet.period[0], "Should end period bet finished."); if (bet.amount[1] == 0) executeRuling(_id, uint(Party.Asker)); else { uint maxAmountToTake = bet.amount[1] * bet.ratio[0] / bet.ratio[1]; uint amountToAsk = maxAmountToTake - bet.amount[1]; address payable asker = address(uint160(bet.parties[1])); require(bet.amount[0] > amountToAsk); asker.send(bet.amount[0] - amountToAsk); bet.amount[0] = amountToAsk; } } /* Section of Claims or Dispute Resolution */ /** @dev Pay the arbitration fee to claim the bet. To be called by the asker. UNTRUSTED. * Note that the arbitrator can have createDispute throw, * which will make this function throw and therefore lead to a party being timed-out. * This is not a vulnerability as the arbitrator can rule in favor of one party anyway. * @param _id The index of the bet. */ function claimAsker(uint _id) public payable { Bet storage bet = bets[_id]; require( bet.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed." ); require(bet.parties[1] == msg.sender, "The caller must be the creator of the bet."); require(now > bet.period[1], "Should claim after the claim period start."); require(now < bet.period[2], "Should claim before the claim period end."); // Amount required to claim: arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); uint claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); // The asker must cover the claim cost. require(msg.value >= claimCost); if(bet.rounds.length == 0) bet.rounds.length++; Round storage round = bet.rounds[0]; round.hasPaid[uint(Party.Asker)] = true; contribute(round, Party.Asker, msg.sender, msg.value, claimCost); // The taker still has to pay. This can also happen if he has paid, // but arbitrationCost has increased. if (round.paidFees[uint(Party.Taker)] <= claimCost) { bet.status = Status.WaitingTaker; emit HasToPayFee(_id, Party.Taker); } else { // The taker has also paid the fee. We create the dispute raiseDispute(_id, arbitrationCost); } } /** @dev Pay the arbitration fee to claim a bet. To be called by the taker. UNTRUSTED. * @param _id The index of the claim. */ function claimTaker(uint _id) public payable { Bet storage bet = bets[_id]; require( bet.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed." ); // NOTE: We assume that for this smart contract version, // this smart contract is vulnerable to a griefing attack. // We expect a very low ratio of griefing attack // in the majority of cases. require( bet.amountTaker[msg.sender] > 0, "The caller must be the one of the taker." ); require(now > bet.period[1], "Should claim after the claim period start."); require(now < bet.period[2], "Should claim before the claim period end."); bet.parties[2] = msg.sender; // Amount required to claim: arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); uint claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); // The taker must cover the claim cost. require(msg.value >= claimCost); if(bet.rounds.length == 0) bet.rounds.length++; Round storage round = bet.rounds[0]; round.hasPaid[uint(Party.Taker)] = true; contribute(round, Party.Taker, msg.sender, msg.value, claimCost); // The taker still has to pay. This can also happen if he has paid, // but arbitrationCost has increased. if (round.paidFees[uint(Party.Taker)] <= claimCost) { bet.status = Status.WaitingAsker; emit HasToPayFee(_id, Party.Taker); } else { // The taker has also paid the fee. We create the dispute. raiseDispute(_id, arbitrationCost); } } /** @dev Make a fee contribution. * @param _round The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. */ function contribute( Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired ) internal { // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)])); _round.contributions[_contributor][uint(_side)] += contribution; _round.paidFees[uint(_side)] += contribution; _round.feeRewards += contribution; // Reimburse leftover ETH. _contributor.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. } /** @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(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Reward asker of the bet if the taker fails to pay the fee. * NOTE: The taker unspent fee are sent to the asker. * @param _id The index of the bet. */ function timeOutByAsker(uint _id) public { Bet storage bet = bets[_id]; require( bet.status == Status.WaitingTaker, "The transaction of the bet must waiting on the taker." ); require( now > bet.period[2], "Timeout claim has not passed yet." ); uint resultRuling = uint(RulingOptions.AskerWins); bet.ruling = Party(resultRuling); executeRuling(_id, resultRuling); } /** @dev Pay taker if the asker fails to pay the fee. * NOTE: The asker unspent fee are sent to the taker. * @param _id The index of the claim. */ function timeOutByTaker(uint _id) public { Bet storage bet = bets[_id]; require( bet.status == Status.WaitingAsker, "The transaction of the bet must waiting on the asker." ); require( now > bet.period[2], "Timeout claim has not passed yet." ); uint resultRuling = uint(RulingOptions.TakerWins); bet.ruling = Party(resultRuling); executeRuling(_id, resultRuling); } /** @dev Create a dispute. UNTRUSTED. * @param _id The index of the bet. * @param _arbitrationCost Amount to pay the arbitrator. */ function raiseDispute(uint _id, uint _arbitrationCost) internal { Bet storage bet = bets[_id]; bet.status = Status.DisputeCreated; uint disputeID = bet.arbitrator.createDispute.value(_arbitrationCost)(AMOUNT_OF_CHOICES, bet.arbitratorExtraData); arbitratorDisputeIDtoBetID[address(bet.arbitrator)][disputeID] = _id; bet.disputeID = disputeID; emit Dispute(bet.arbitrator, bet.disputeID, _id, _id); } /** @dev Submit a reference to evidence. EVENT. * @param _id The index of the claim. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(uint _id, string memory _evidence) public { Bet storage bet = bets[_id]; require( msg.sender == bet.parties[1] || bet.amountTaker[msg.sender] > 0, "The caller must be the asker or a taker." ); require( bet.status >= Status.DisputeCreated, "The dispute has not been created yet." ); emit Evidence(bet.arbitrator, _id, msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. TRUSTED. * @param _id The ID of the bet with the request to fund. * @param _side The recipient of the contribution. */ function fundAppeal(uint _id, Party _side) external payable { // Recipient must be either the requester or challenger. require(_side == Party.Asker || _side == Party.Taker); // solium-disable-line error-reason Bet storage bet = bets[_id]; require( bet.status >= Status.DisputeCreated, "A dispute must have been raised to fund an appeal." ); (uint appealPeriodStart, uint appealPeriodEnd) = bet.arbitrator.appealPeriod(bet.disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Contributions must be made within the appeal period." ); Round storage round = bet.rounds[bet.rounds.length - 1]; Party winner = Party(bet.arbitrator.currentRuling(bet.disputeID)); Party loser; if (winner == Party.Asker) loser = Party.Taker; else if (winner == Party.Taker) loser = Party.Asker; require(!(_side==loser) || (now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2), "The loser must contribute during the first half of the appeal period."); uint multiplier; if (_side == winner) multiplier = bet.stakeMultiplier[1]; else if (_side == loser) multiplier = bet.stakeMultiplier[2]; else multiplier = bet.stakeMultiplier[0]; uint appealCost = bet.arbitrator.appealCost(bet.disputeID, bet.arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); contribute(round, _side, msg.sender, msg.value, totalCost); if (round.paidFees[uint(_side)] >= totalCost) round.hasPaid[uint(_side)] = true; // Raise appeal if both sides are fully funded. if (round.hasPaid[uint(Party.Taker)] && round.hasPaid[uint(Party.Asker)]) { bet.arbitrator.appeal.value(appealCost)(bet.disputeID, bet.arbitratorExtraData); bet.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); } } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) external { Party resultRuling = Party(_ruling); uint id = arbitratorDisputeIDtoBetID[msg.sender][_disputeID]; Bet storage bet = bets[id]; require(_ruling <= AMOUNT_OF_CHOICES); // solium-disable-line error-reason require(address(bet.arbitrator) == msg.sender); // solium-disable-line error-reason require(bet.status != Status.Resolved); // solium-disable-line error-reason Round storage round = bet.rounds[bet.rounds.length - 1]; // The ruling is inverted if the loser paid its fees. // If one side paid its fees, the ruling is in its favor. // Note that if the other side had also paid, an appeal would have been created. if (round.hasPaid[uint(Party.Asker)] == true) resultRuling = Party.Asker; else if (round.hasPaid[uint(Party.Taker)] == true) resultRuling = Party.Taker; bet.status = Status.Resolved; bet.ruling = resultRuling; emit Ruling(Arbitrator(msg.sender), _disputeID, uint(resultRuling)); executeRuling(id, uint(resultRuling)); } /** @dev Reimburses contributions if no disputes were raised. * If a dispute was raised, sends the fee stake and the reward for the winner. * @param _beneficiary The address that made contributions to a request. * @param _id The ID of the bet. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards( address payable _beneficiary, uint _id, uint _round ) public { Bet storage bet = bets[_id]; Round storage round = bet.rounds[_round]; // The request must be resolved. require(bet.status == Status.Resolved); // solium-disable-line error-reason uint reward; if (!round.hasPaid[uint(Party.Asker)] || !round.hasPaid[uint(Party.Taker)]) { // Reimburse if not enough fees were raised to appeal the ruling. reward = round.contributions[_beneficiary][uint(Party.Asker)] + round.contributions[_beneficiary][uint(Party.Taker)]; round.contributions[_beneficiary][uint(Party.Asker)] = 0; round.contributions[_beneficiary][uint(Party.Taker)] = 0; if(bet.amountTaker[_beneficiary] > 0 && bet.ruling != Party.Asker) { reward += bet.amountTaker[_beneficiary] * bet.ratio[0] / bet.ratio[1]; bet.amountTaker[_beneficiary] = 0; } } else if (bet.ruling == Party.None) { // No disputes were raised, or there isn't a winner and loser. Reimburse unspent fees proportionally. uint rewardAsker = round.paidFees[uint(Party.Asker)] > 0 ? (round.contributions[_beneficiary][uint(Party.Asker)] * round.feeRewards) / (round.paidFees[uint(Party.Taker)] + round.paidFees[uint(Party.Asker)]) : 0; uint rewardTaker = round.paidFees[uint(Party.Taker)] > 0 ? (round.contributions[_beneficiary][uint(Party.Taker)] * round.feeRewards) / (round.paidFees[uint(Party.Taker)] + round.paidFees[uint(Party.Asker)]) : 0; reward = rewardAsker + rewardTaker; round.contributions[_beneficiary][uint(Party.Asker)] = 0; round.contributions[_beneficiary][uint(Party.Taker)] = 0; // Reimburse the fund bet. if(bet.amountTaker[_beneficiary] > 0) { reward += bet.amountTaker[_beneficiary]; bet.amountTaker[_beneficiary] = 0; } } else { // Reward the winner. reward = round.paidFees[uint(bet.ruling)] > 0 ? (round.contributions[_beneficiary][uint(bet.ruling)] * round.feeRewards) / round.paidFees[uint(bet.ruling)] : 0; round.contributions[_beneficiary][uint(bet.ruling)] = 0; if(bet.amountTaker[_beneficiary] > 0 && bet.ruling != Party.Asker) { reward += bet.amountTaker[_beneficiary] * bet.ratio[0] / bet.ratio[1]; bet.amountTaker[_beneficiary] = 0; } } emit RewardWithdrawal(_id, _beneficiary, _round, reward); _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Execute a ruling of a dispute. It reimburses the fee to the winning party. * @param _id The index of the bet. * @param _ruling Ruling given by the arbitrator. 1 : Reimburse the owner of the item. 2 : Pay the finder. */ function executeRuling(uint _id, uint _ruling) internal { require(_ruling <= AMOUNT_OF_CHOICES, "Invalid ruling."); Bet storage bet = bets[_id]; bet.status = Status.Resolved; address payable asker = address(uint160(bet.parties[1])); address payable taker = address(uint160(bet.parties[2])); if (_ruling == uint(Party.None)) { if(bet.amount[0] > 0) { asker.send(bet.amount[0]); bet.amount[0] = 0; } if (bet.rounds.length != 0) { withdrawFeesAndRewards(asker, _id, 0); withdrawFeesAndRewards(taker, _id, 0); } } else if (_ruling == uint(Party.Asker)) { require(bet.amount[0] > 0); asker.send(bet.amount[0] + bet.amount[1]); bet.amount[0] = 0; bet.amount[1] = 0; if (bet.rounds.length != 0) withdrawFeesAndRewards(asker, _id, 0); } else { if (bet.rounds.length != 0) withdrawFeesAndRewards(taker, _id, 0); } } /* Governance */ /** @dev Change the governor of the token curated registry. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** @dev Change the address of the goal bet registry contract. * @param _betArbitrableList The address of the new goal bet registry contract. */ function changeArbitrationBetList(address _betArbitrableList) external onlyGovernor { betArbitrableList = _betArbitrableList; } // **************************** // // * View functions * // // **************************** // /** @dev Get the claim cost * @param _id The index of the claim. */ function getClaimCost(uint _id) external view returns (uint claimCost) { Bet storage bet = bets[_id]; uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); } function getMaxAmountToBet( uint _id ) external view returns (uint maxAmountToBet) { Bet storage bet = bets[_id]; maxAmountToBet = bet.amount[0]*bet.amount[0] / (bet.ratio[0]*bet.amount[0] / bet.ratio[1] - bet.amount[0]) - bet.amount[1]; } /** @dev Return the values of the bets the query finds. This function is O(n), where n is the number of bets. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _cursor The bet index from which to start iterating. To start from either the oldest or newest item. * @param _count The number of bets to return. * @param _filter The filter to use. Each element of the array in sequence means: * - Include absent bets in result. * - Include registered bets in result. * - Include bets with registration requests that are not disputed in result. * - Include bets with clearing requests that are not disputed in result. * - Include disputed bets with registration requests in result. * - Include disputed bets with clearing requests in result. * - Include bets submitted by the caller. * - Include bets challenged by the caller. * - Include bets created. * - Include bets taken. * @return The values of the bets found and whether there are more bets for the current filter and sort. */ function queryBets(uint _cursor, uint _count, bool[10] calldata _filter) external view returns (uint[] memory values, bool hasMore) { values = new uint[](_count); uint index = 0; for ( uint i = _cursor == 0 ? bets.length - 1 : bets.length - 1 - _cursor; i < bets.length; i++ ) { Bet storage bet = bets[i]; ArbitrableBetList betArbitrableListInstance = ArbitrableBetList(betArbitrableList); (ArbitrableBetList.BetStatus arbitrableBetlistStatus, uint numberOfRequests) = betArbitrableListInstance.getBetInfo(i); (bool disputed, , , , address[3] memory parties, , , , ) = betArbitrableListInstance.getRequestInfo(i, numberOfRequests - 1); if ( /* solium-disable operator-whitespace */ (_filter[0] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.Absent) || (_filter[1] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.Registered) || (_filter[2] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.RegistrationRequested && !disputed) || (_filter[3] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.ClearingRequested && !disputed) || (_filter[4] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.RegistrationRequested && disputed) || (_filter[5] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.ClearingRequested && disputed) || (_filter[6] && parties[1] == msg.sender) || // My Submissions. (_filter[7] && parties[2] == msg.sender) || // My Challenges. (_filter[8] && bet.parties[1] == msg.sender) || // My bets. (_filter[9] && bet.parties[2] == msg.sender) // My taken bets. /* solium-enable operator-whitespace */ ) { if (index < _count) { values[index] = i; index++; } else { hasMore = true; break; } } } } }
Returns the contribution value and remainder from available ETH and required amount. _available The amount of ETH available for the contribution. _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(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) remainder = _available - _requiredAmount; return (_requiredAmount, remainder); }
12,937,029
// File: @openzeppelin/[email protected]/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/[email protected]/utils/Counters.sol pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint _value; // default: 0 } function current(Counter storage counter) internal view returns (uint) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint value = counter._value; require(value > 0, 'Counter: decrement overflow'); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/[email protected]/utils/cryptography/ECDSA.sol pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @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. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return recover(hash, r, vs); } else { revert('ECDSA: invalid signature length'); } } /** * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), 'ECDSA: invalid signature'); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); } } // File: @openzeppelin/[email protected]/utils/cryptography/draft-EIP712.sol pragma solidity ^0.8.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 */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // File: @openzeppelin/[email protected]/token/ERC20/extensions/draft-IERC20Permit.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint value, uint 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 (uint); /** * @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); } // File: @openzeppelin/[email protected]/utils/structs/EnumerableSet.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint) _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 uint 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}. uint toDeleteIndex = valueIndex - 1; uint lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint) { 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, uint index) private view returns (bytes32) { 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 (uint) { 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, uint 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(uint(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint) { 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, uint index) internal view returns (address) { return address(uint160(uint(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint 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, uint 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, uint 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 (uint) { 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, uint index) internal view returns (uint) { return uint(_at(set._inner, index)); } } // File: @openzeppelin/[email protected]/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/[email protected]/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/[email protected]/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(uint 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'; } uint temp = value; uint digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint temp = value; uint 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(uint value, uint length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint 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/[email protected]/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/[email protected]/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/[email protected]/token/ERC20/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: @openzeppelin/[email protected]/access/AccessControl.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/[email protected]/access/AccessControlEnumerable.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // File: @openzeppelin/[email protected]/security/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/[email protected]/token/ERC20/extensions/ERC20Pausable.sol pragma solidity ^0.8.0; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // File: @openzeppelin/[email protected]/token/ERC20/extensions/ERC20Burnable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // File: @openzeppelin/[email protected]/token/ERC20/extensions/draft-ERC20Permit.sol pragma solidity ^0.8.0; /** * @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 { using Counters for Counters.Counter; mapping(address => Counters.Counter) 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 { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-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) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // File: @openzeppelin/[email protected]/token/ERC20/presets/ERC20PresetMinterPauser.sol pragma solidity ^0.8.0; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // File: BetaToken.sol pragma solidity 0.8.6; contract BetaToken is ERC20PresetMinterPauser('Beta Token', 'BETA'), ERC20Permit('BETA') { function _beforeTokenTransfer( address from, address to, uint amount ) internal virtual override(ERC20, ERC20PresetMinterPauser) { ERC20PresetMinterPauser._beforeTokenTransfer(from, to, amount); } }
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. Documentation for signature generation:/ Check the signature length - case 65: r,s,v signature (standard) - case 64: r,vs signature (cf https:eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ ecrecover takes the signature parameters, and the only way to get them currently is to use assembly. ecrecover takes the signature parameters, and the only way to get them currently is to use assembly.
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); bytes32 r; bytes32 vs; assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return recover(hash, r, vs); revert('ECDSA: invalid signature length'); } }
5,851,657
./full_match/137/0x8B17A6f80db8cbCda803201C5e5b4E9451e06ccB/sources/contracts/SmartAlphaLoupe.sol
Return the amount of redeemable junior underlying for a user in a SMART Alpha system This should be called statically on frontend smartAlphaAddress The address of the SMART Alpha system in which to check user The address of the user for which to check return The amount of redeemable junior underlying
function userRedeemableJuniorUnderlying(address smartAlphaAddress, address user) external returns (uint256) { SmartAlpha sa = SmartAlpha(smartAlphaAddress); sa.advanceEpoch(); (uint256 epoch, uint256 amount) = sa.juniorExitQueue(user); if (amount == 0 || epoch >= sa.epoch()) { return 0; } uint256 price = sa.history_epochJuniorTokenPrice(epoch); return amount * price / scaleFactor; }
3,764,664
/** * Source Code first verified at https://etherscan.io * WorldTrade asset Smart Contract v4.1 */ pragma solidity ^0.4.16; /* * @title Standard Token Contract * * ERC20-compliant tokens => https://github.com/ethereum/EIPs/issues/20 * A token is a fungible virtual good that can be traded. * ERC-20 Tokens comply to the standard described in the Ethereum ERC-20 proposal. * Basic, standardized Token contract. Defines the functions to check token balances * send tokens, send tokens on behalf of a 3rd party and the corresponding approval process. * */ contract Token { // **** BASE FUNCTIONALITY // @notice For debugging purposes when using solidity online browser function whoAmI() constant returns (address) { return msg.sender; } // SC owners: address owner; function isOwner() returns (bool) { if (msg.sender == owner) return true; return false; } // **** EVENTS // @notice A generic error log event Error(string error); // **** DATA mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public initialSupply; // Initial and total token supply uint256 public totalSupply; // bool allocated = false; // True after defining token parameters and initial mint // Public variables of the token, all used for display // HumanStandardToken is a specialisation of ERC20 defining these parameters string public name; string public symbol; uint8 public decimals; string public standard = 'H0.1'; // **** METHODS // Get total amount of tokens, totalSupply is a public var actually // function totalSupply() constant returns (uint256 totalSupply) {} // Get the account balance of another account with address _owner function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // Send _amount amount of tokens to address _to function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] < _amount) { Error('transfer: the amount to transfer is higher than your token balance'); return false; } balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } // Send _amount 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 function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { if (balances[_from] < _amount) { Error('transfer: the amount to transfer is higher than the token balance of the source'); return false; } if (allowed[_from][msg.sender] < _amount) { Error('transfer: the amount to transfer is higher than the maximum token transfer allowed by the source'); return false; } balances[_from] -= _amount; balances[_to] += _amount; allowed[_from][msg.sender] -= _amount; Transfer(_from, _to, _amount); return true; } // Allow _spender to withdraw from your account, multiple times, up to the _amount amount. // If this function is called again it overwrites the current allowance with _amount. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // Constructor: set up token properties and owner token balance function Token() { // This is the constructor, so owner should be equal to msg.sender, and this method should be called just once owner = msg.sender; // make sure owner address is configured // if(owner == 0x0) throw; // owner address can call this function // if (msg.sender != owner ) throw; // call this function just once // if (allocated) throw; initialSupply = 50000000 * 1000000; // 50M tokens, 6 decimals totalSupply = initialSupply; name = "WorldTrade"; symbol = "WTE"; decimals = 6; balances[owner] = totalSupply; Transfer(this, owner, totalSupply); // allocated = true; } // **** EVENTS // Triggered when tokens are transferred event Transfer(address indexed _from, address indexed _to, uint256 _amount); // Triggered whenever approve(address _spender, uint256 _amount) is called event Approval(address indexed _owner, address indexed _spender, uint256 _amount); } // Interface of issuer contract, just to cast the contract address and make it callable from the asset contract contract IFIssuers { // **** DATA // **** FUNCTIONS function isIssuer(address _issuer) constant returns (bool); } contract Asset is Token { // **** DATA /** Asset states * * - Released: Once issued the asset stays as released until sent for free to someone specified by issuer * - ForSale: The asset belongs to a user and is open to be sold * - Unfungible: The asset cannot be sold, remaining to the user it belongs to. */ enum assetStatus { Released, ForSale, Unfungible } // https://ethereum.stackexchange.com/questions/1807/enums-in-solidity struct asst { uint256 assetId; address assetOwner; address issuer; string content; // a JSON object containing the image data of the asset and its title uint256 sellPrice; // in WorldTrade tokens, how many of them for this asset assetStatus status; // behaviour (tradability) of the asset depends upon its status } mapping (uint256 => asst) assetsById; uint256 lastAssetId; // Last assetId address public SCIssuers; // Contract that defines who is an issuer and who is not uint256 assetFeeIssuer; // Fee percentage for Issuer on every asset sale transaction uint256 assetFeeWorldTrade; // Fee percentage for WorldTrade on every asset sale transaction // **** METHODS // Constructor function Asset(address _SCIssuers) { SCIssuers = _SCIssuers; } // Queries the asset, knowing the id function getAssetById(uint256 assetId) constant returns (uint256 _assetId, address _assetOwner, address _issuer, string _content, uint256 _sellPrice, uint256 _status) { return (assetsById[assetId].assetId, assetsById[assetId].assetOwner, assetsById[assetId].issuer, assetsById[assetId].content, assetsById[assetId].sellPrice, uint256(assetsById[assetId].status)); } // Seller sends an owned asset to a buyer, providing its allowance matches token price and transfer the tokens from buyer function sendAssetTo(uint256 assetId, address assetBuyer) returns (bool) { // assetId must not be zero if (assetId == 0) { Error('sendAssetTo: assetId must not be zero'); return false; } // Check whether the asset belongs to the seller if (assetsById[assetId].assetOwner != msg.sender) { Error('sendAssetTo: the asset does not belong to you, the seller'); return false; } if (assetsById[assetId].sellPrice > 0) { // for non-null token paid transactions // Check whether there is balance enough from the buyer to get its tokens if (balances[assetBuyer] < assetsById[assetId].sellPrice) { Error('sendAssetTo: there is not enough balance from the buyer to get its tokens'); return false; } // Check whether there is allowance enough from the buyer to get its tokens if (allowance(assetBuyer, msg.sender) < assetsById[assetId].sellPrice) { Error('sendAssetTo: there is not enough allowance from the buyer to get its tokens'); return false; } // Get the buyer tokens if (!transferFrom(assetBuyer, msg.sender, assetsById[assetId].sellPrice)) { Error('sendAssetTo: transferFrom failed'); // This shouldn't happen ever, but just in case... return false; } } // Set the asset status to Unfungible assetsById[assetId].status = assetStatus.Unfungible; // Transfer the asset to the buyer assetsById[assetId].assetOwner = assetBuyer; // Event log SendAssetTo(assetId, assetBuyer); return true; } // Buyer gets an asset providing it is in ForSale status, and pays the corresponding tokens to the seller/owner. amount must match assetPrice to have a deal. function buyAsset(uint256 assetId, uint256 amount) returns (bool) { // assetId must not be zero if (assetId == 0) { Error('buyAsset: assetId must not be zero'); return false; } // Check whether the asset is in ForSale status if (assetsById[assetId].status != assetStatus.ForSale) { Error('buyAsset: the asset is not for sale'); return false; } // Check whether the asset price is the same as amount if (assetsById[assetId].sellPrice != amount) { Error('buyAsset: the asset price does not match the specified amount'); return false; } if (assetsById[assetId].sellPrice > 0) { // for non-null token paid transactions // Check whether there is balance enough from the buyer to pay the asset if (balances[msg.sender] < assetsById[assetId].sellPrice) { Error('buyAsset: there is not enough token balance to buy this asset'); return false; } // Calculate the seller income uint256 sellerIncome = assetsById[assetId].sellPrice * (1000 - assetFeeIssuer - assetFeeWorldTrade) / 1000; // Send the buyer's tokens to the seller if (!transfer(assetsById[assetId].assetOwner, sellerIncome)) { Error('buyAsset: seller token transfer failed'); // This shouldn't happen ever, but just in case... return false; } // Send the issuer's fee uint256 issuerIncome = assetsById[assetId].sellPrice * assetFeeIssuer / 1000; if (!transfer(assetsById[assetId].issuer, issuerIncome)) { Error('buyAsset: issuer token transfer failed'); // This shouldn't happen ever, but just in case... return false; } // Send the WorldTrade's fee uint256 WorldTradeIncome = assetsById[assetId].sellPrice * assetFeeWorldTrade / 1000; if (!transfer(owner, WorldTradeIncome)) { Error('buyAsset: WorldTrade token transfer failed'); // This shouldn't happen ever, but just in case... return false; } } // Set the asset status to Unfungible assetsById[assetId].status = assetStatus.Unfungible; // Transfer the asset to the buyer assetsById[assetId].assetOwner = msg.sender; // Event log BuyAsset(assetId, amount); return true; } // To limit issue functions just to authorized issuers modifier onlyIssuer() { if (!IFIssuers(SCIssuers).isIssuer(msg.sender)) { Error('onlyIssuer function called by user that is not an authorized issuer'); } else { _; } } // To be called by issueAssetTo() and properly authorized issuers function issueAsset(string content, uint256 sellPrice) onlyIssuer internal returns (uint256 nextAssetId) { // Find out next asset Id nextAssetId = lastAssetId + 1; assetsById[nextAssetId].assetId = nextAssetId; assetsById[nextAssetId].assetOwner = msg.sender; assetsById[nextAssetId].issuer = msg.sender; assetsById[nextAssetId].content = content; assetsById[nextAssetId].sellPrice = sellPrice; assetsById[nextAssetId].status = assetStatus.Released; // Update lastAssetId lastAssetId++; // Event log IssueAsset(nextAssetId, msg.sender, sellPrice); return nextAssetId; } // Issuer sends a new free asset to a given user as a gift function issueAssetTo(string content, address to) returns (bool) { uint256 assetId = issueAsset(content, 0); // 0 tokens, as a gift if (assetId == 0) { Error('issueAssetTo: asset has not been properly issued'); return (false); } // The brand new asset is inmediatly sent to the recipient return(sendAssetTo(assetId, to)); } // Seller can block tradability of its assets function setAssetUnfungible(uint256 assetId) returns (bool) { // assetId must not be zero if (assetId == 0) { Error('setAssetUnfungible: assetId must not be zero'); return false; } // Check whether the asset belongs to the caller if (assetsById[assetId].assetOwner != msg.sender) { Error('setAssetUnfungible: only owners of the asset are allowed to update its status'); return false; } assetsById[assetId].status = assetStatus.Unfungible; // Event log SetAssetUnfungible(assetId, msg.sender); return true; } // Seller updates the price of its assets and its status to ForSale function setAssetPrice(uint256 assetId, uint256 sellPrice) returns (bool) { // assetId must not be zero if (assetId == 0) { Error('setAssetPrice: assetId must not be zero'); return false; } // Check whether the asset belongs to the caller if (assetsById[assetId].assetOwner != msg.sender) { Error('setAssetPrice: only owners of the asset are allowed to set its price and update its status'); return false; } assetsById[assetId].sellPrice = sellPrice; assetsById[assetId].status = assetStatus.ForSale; // Event log SetAssetPrice(assetId, msg.sender, sellPrice); return true; } // Owner updates the fees for assets sale transactions function setAssetSaleFees(uint256 feeIssuer, uint256 feeWorldTrade) returns (bool) { // Check this is called by owner if (!isOwner()) { Error('setAssetSaleFees: only Owner is authorized to update asset sale fees.'); return false; } // Check new fees are consistent if (feeIssuer + feeWorldTrade > 1000) { Error('setAssetSaleFees: added fees exceed 100.0%. Not updated.'); return false; } assetFeeIssuer = feeIssuer; assetFeeWorldTrade = feeWorldTrade; // Event log SetAssetSaleFees(feeIssuer, feeWorldTrade); return true; } // **** EVENTS // Triggered when a seller sends its asset to a buyer and receives the corresponding tokens event SendAssetTo(uint256 assetId, address assetBuyer); // Triggered when a buyer sends its tokens to a seller and receives the specified asset event BuyAsset(uint256 assetId, uint256 amount); // Triggered when the admin issues a new asset event IssueAsset(uint256 nextAssetId, address assetOwner, uint256 sellPrice); // Triggered when the user updates its asset status to Unfungible event SetAssetUnfungible(uint256 assetId, address assetOwner); // Triggered when the user updates its asset price and status to ForSale event SetAssetPrice(uint256 assetId, address assetOwner, uint256 sellPrice); // Triggered when the owner updates the asset sale fees event SetAssetSaleFees(uint256 feeIssuer, uint256 feeWorldTrade); }
Queries the asset, knowing the id
function getAssetById(uint256 assetId) constant returns (uint256 _assetId, address _assetOwner, address _issuer, string _content, uint256 _sellPrice, uint256 _status) { return (assetsById[assetId].assetId, assetsById[assetId].assetOwner, assetsById[assetId].issuer, assetsById[assetId].content, assetsById[assetId].sellPrice, uint256(assetsById[assetId].status)); }
2,487,279
// SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/skale-manager-interfaces/ISkaleDKG.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./utils/Random.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions, ISchainsInternal { using Random for IRandom.RandomGenerator; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public override isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public override schainsAtSystem; uint64 public override numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; mapping (uint => bytes32[]) private _nodeToLockedSchains; mapping (bytes32 => uint[]) private _schainToExceptionNodes; EnumerableSetUpgradeable.UintSet private _keysOfSchainTypes; uint public currentGeneration; bytes32 public constant SCHAIN_TYPE_MANAGER_ROLE = keccak256("SCHAIN_TYPE_MANAGER_ROLE"); bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE"); bytes32 public constant GENERATION_MANAGER_ROLE = keccak256("GENERATION_MANAGER_ROLE"); modifier onlySchainTypeManager() { require(hasRole(SCHAIN_TYPE_MANAGER_ROLE, msg.sender), "SCHAIN_TYPE_MANAGER_ROLE is required"); _; } modifier onlyDebugger() { require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required"); _; } modifier onlyGenerationManager() { require(hasRole(GENERATION_MANAGER_ROLE, msg.sender), "GENERATION_MANAGER_ROLE is required"); _; } modifier schainExists(bytes32 schainHash) { require(isSchainExist(schainHash), "The schain does not exist"); _; } /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, address originator, uint lifetime, uint deposit ) external override allow("Schains") { bytes32 schainHash = keccak256(abi.encodePacked(name)); schains[schainHash] = Schain({ name: name, owner: from, indexInOwnerList: schainIndexes[from].length, partOfNode: 0, startDate: block.timestamp, startBlock: block.number, lifetime: lifetime, deposit: deposit, index: numberOfSchains, generation: currentGeneration, originator: originator }); isSchainActive[schainHash] = true; numberOfSchains++; schainIndexes[from].push(schainHash); schainsAtSystem.push(schainHash); usedSchainNames[schainHash] = true; } /** * @dev Allows Schain contract to create a node group for an schain. * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function createGroupForSchain( bytes32 schainHash, uint numberOfNodes, uint8 partOfNode ) external override allow("Schains") schainExists(schainHash) returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainHash].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources + numberOfNodes * constantsHolder.TOTAL_SPACE_ON_NODE() / partOfNode; } return _generateGroup(schainHash, numberOfNodes); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function changeLifetime( bytes32 schainHash, uint lifetime, uint deposit ) external override allow("Schains") schainExists(schainHash) { schains[schainHash].deposit = schains[schainHash].deposit + deposit; schains[schainHash].lifetime = schains[schainHash].lifetime + lifetime; } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function removeSchain(bytes32 schainHash, address from) external override allow("Schains") schainExists(schainHash) { isSchainActive[schainHash] = false; uint length = schainIndexes[from].length; uint index = schains[schainHash].indexInOwnerList; if (index != length - 1) { bytes32 lastSchainHash = schainIndexes[from][length - 1]; schains[lastSchainHash].indexInOwnerList = index; schainIndexes[from][index] = lastSchainHash; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainHash) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length - 1]; break; } } schainsAtSystem.pop(); delete schains[schainHash]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. * * Requirements: * * - Message sender is Schains, SkaleDKG or NodeRotation smart contract * - Schain must exist */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external override allowThree("NodeRotation", "SkaleDKG", "Schains") schainExists(schainHash) { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length - 1; if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } removeSchainForNode(nodeIndex, placeOfSchainOnNode[schainHash][nodeIndex] - 1); delete placeOfSchainOnNode[schainHash][nodeIndex]; INodes nodes = INodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, schains[schainHash].partOfNode); } /** * @dev Allows Schains contract to delete a group of schains * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function deleteGroup(bytes32 schainHash) external override allow("Schains") schainExists(schainHash) { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainHash]; skaleDKG.deleteChannel(schainHash); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. * * Requirements: * * - Message sender is Schains or NodeRotation smart contract * - Schain must exist */ function setException( bytes32 schainHash, uint nodeIndex ) external override allowTwo("Schains", "NodeRotation") schainExists(schainHash) { _setException(schainHash, nodeIndex); } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. * * Requirements: * * - Message sender is Schains or NodeRotation smart contract * - Schain must exist */ function setNodeInGroup( bytes32 schainHash, uint nodeIndex ) external override allowTwo("Schains", "NodeRotation") schainExists(schainHash) { if (holesForSchains[schainHash].length == 0) { schainsGroups[schainHash].push(nodeIndex); } else { schainsGroups[schainHash][holesForSchains[schainHash][0]] = nodeIndex; uint min = type(uint).max; uint index = 0; for (uint i = 1; i < holesForSchains[schainHash].length; i++) { if (min > holesForSchains[schainHash][i]) { min = holesForSchains[schainHash][i]; index = i; } } if (min == type(uint).max) { delete holesForSchains[schainHash]; } else { holesForSchains[schainHash][0] = min; holesForSchains[schainHash][index] = holesForSchains[schainHash][holesForSchains[schainHash].length - 1]; holesForSchains[schainHash].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains * * Requirements: * * - Message sender is Schains smart contract * - Schain must exist */ function removeHolesForSchain(bytes32 schainHash) external override allow("Schains") schainExists(schainHash) { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external override onlySchainTypeManager { require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added"); schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; emit SchainTypeAdded(numberOfSchainTypes, partOfNode, numberOfNodes); } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external override onlySchainTypeManager { require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed"); delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; emit SchainTypeRemoved(typeOfSchain); } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external override onlySchainTypeManager { numberOfSchainTypes = newNumberOfSchainTypes; } function removeNodeFromAllExceptionSchains(uint nodeIndex) external override allow("SkaleManager") { uint len = _nodeToLockedSchains[nodeIndex].length; for (uint i = len; i > 0; i--) { removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex); } } /** * @dev Clear list of nodes that can't be chosen to schain with id {schainHash} */ function removeAllNodesFromSchainExceptions(bytes32 schainHash) external override allow("Schains") { for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; ++i) { removeNodeFromExceptions(schainHash, _schainToExceptionNodes[schainHash][i]); } } /** * @dev Mark all nodes in the schain as invisible * * Requirements: * * - Message sender is NodeRotation or SkaleDKG smart contract * - Schain must exist */ function makeSchainNodesInvisible( bytes32 schainHash ) external override allowTwo("NodeRotation", "SkaleDKG") schainExists(schainHash) { INodes nodes = INodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) { nodes.makeNodeInvisible(_schainToExceptionNodes[schainHash][i]); } } /** * @dev Mark all nodes in the schain as visible * * Requirements: * * - Message sender is NodeRotation or SkaleDKG smart contract * - Schain must exist */ function makeSchainNodesVisible( bytes32 schainHash ) external override allowTwo("NodeRotation", "SkaleDKG") schainExists(schainHash) { _makeSchainNodesVisible(schainHash); } /** * @dev Increments generation for all new schains * * Requirements: * * - Sender must be granted with GENERATION_MANAGER_ROLE */ function newGeneration() external override onlyGenerationManager { currentGeneration += 1; } /** * @dev Returns all Schains in the network. */ function getSchains() external view override returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. * * Requirements: * * - Schain must exist */ function getSchainsPartOfNode(bytes32 schainHash) external view override schainExists(schainHash) returns (uint8) { return schains[schainHash].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view override returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainHashesByAddress(address from) external view override returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view override returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainHashesForNode(uint nodeIndex) external view override returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view override returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. * * Requirements: * * - Schain must exist */ function getSchainOwner(bytes32 schainHash) external view override schainExists(schainHash) returns (address) { return schains[schainHash].owner; } /** * @dev Returns an originator of the schain. * * Requirements: * * - Schain must exist */ function getSchainOriginator(bytes32 schainHash) external view override schainExists(schainHash) returns (address) { require(schains[schainHash].originator != address(0), "Originator address is not set"); return schains[schainHash].originator; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view override returns (bool) { bytes32 schainHash = keccak256(abi.encodePacked(name)); return schains[schainHash].owner == address(0) && !usedSchainNames[schainHash] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")) && bytes(name).length > 0; } /** * @dev Checks whether schain lifetime has expired. * * Requirements: * * - Schain must exist */ function isTimeExpired(bytes32 schainHash) external view override schainExists(schainHash) returns (bool) { return uint(schains[schainHash].startDate) + schains[schainHash].lifetime < block.timestamp; } /** * @dev Checks whether address is owner of schain. * * Requirements: * * - Schain must exist */ function isOwnerAddress( address from, bytes32 schainHash ) external view override schainExists(schainHash) returns (bool) { return schains[schainHash].owner == from; } /** * @dev Returns schain name. * * Requirements: * * - Schain must exist */ function getSchainName(bytes32 schainHash) external view override schainExists(schainHash) returns (string memory) { return schains[schainHash].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view override returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view override returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. * * Requirements: * * - Schain must exist */ function getNumberOfNodesInGroup(bytes32 schainHash) external view override schainExists(schainHash) returns (uint) { return schainsGroups[schainHash].length; } /** * @dev Returns nodes in an schain group. * * Requirements: * * - Schain must exist */ function getNodesInGroup(bytes32 schainHash) external view override schainExists(schainHash) returns (uint[] memory) { return schainsGroups[schainHash]; } /** * @dev Checks whether sender is a node address from a given schain group. * * Requirements: * * - Schain must exist */ function isNodeAddressesInGroup( bytes32 schainHash, address sender ) external view override schainExists(schainHash) returns (bool) { INodes nodes = INodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainHash].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainHash][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. * * Requirements: * * - Schain must exist */ function getNodeIndexInGroup( bytes32 schainHash, uint nodeId ) external view override schainExists(schainHash) returns (uint) { for (uint index = 0; index < schainsGroups[schainHash].length; index++) { if (schainsGroups[schainHash][index] == nodeId) { return index; } } return schainsGroups[schainHash].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. * * Requirements: * * - Schain must exist */ function isAnyFreeNode(bytes32 schainHash) external view override schainExists(schainHash) returns (bool) { INodes nodes = INodes(contractManager.getContract("Nodes")); uint8 space = schains[schainHash].partOfNode; return nodes.countNodesWithFreeSpace(space) > 0; } /** * @dev Returns whether any exceptions exist for node in a schain group. * * Requirements: * * - Schain must exist */ function checkException(bytes32 schainHash, uint nodeIndex) external view override schainExists(schainHash) returns (bool) { return _exceptionsForGroups[schainHash][nodeIndex]; } /** * @dev Checks if the node is in holes for the schain * * Requirements: * * - Schain must exist */ function checkHoleForSchain( bytes32 schainHash, uint indexOfNode ) external view override schainExists(schainHash) returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Checks if the node is assigned for the schain * * Requirements: * * - Schain must exist */ function checkSchainOnNode( uint nodeIndex, bytes32 schainHash ) external view override schainExists(schainHash) returns (bool) { return placeOfSchainOnNode[schainHash][nodeIndex] != 0; } function getSchainType(uint typeOfSchain) external view override returns(uint8, uint) { require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain"); return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes); } /** * @dev Returns generation of a particular schain * * Requirements: * * - Schain must exist */ function getGeneration(bytes32 schainHash) external view override schainExists(schainHash) returns (uint) { return schains[schainHash].generation; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. * * Requirements: * * - Message sender is Schains or NodeRotation smart contract * - Schain must exist */ function addSchainForNode( uint nodeIndex, bytes32 schainHash ) public override allowTwo("Schains", "NodeRotation") schainExists(schainHash) { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainHash); placeOfSchainOnNode[schainHash][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainHash; placeOfSchainOnNode[schainHash][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public override allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length - 1) { schainsForNodes[nodeIndex].pop(); } else { delete schainsForNodes[nodeIndex][schainIndex]; if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Allows Schains contract to remove node from exceptions * * Requirements: * * - Message sender is Schains, NodeRotation or SkaleManager smart contract * - Schain must exist */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) public override allowThree("Schains", "NodeRotation", "SkaleManager") schainExists(schainHash) { _exceptionsForGroups[schainHash][nodeIndex] = false; uint len = _nodeToLockedSchains[nodeIndex].length; for (uint i = len; i > 0; i--) { if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) { if (i != len) { _nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1]; } _nodeToLockedSchains[nodeIndex].pop(); break; } } len = _schainToExceptionNodes[schainHash].length; for (uint i = len; i > 0; i--) { if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) { if (i != len) { _schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1]; } _schainToExceptionNodes[schainHash].pop(); break; } } } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainHash) public view override returns (bool) { return bytes(schains[schainHash].name).length != 0; } function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) { return _nodeToLockedSchains; } function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) { return _schainToExceptionNodes; } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainHash, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { INodes nodes = INodes(contractManager.getContract("Nodes")); uint8 space = schains[schainHash].partOfNode; nodesInGroup = new uint[](numberOfNodes); require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain"); IRandom.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainHash) ); for (uint i = 0; i < numberOfNodes; i++) { uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); nodesInGroup[i] = node; _setException(schainHash, node); addSchainForNode(node, schainHash); nodes.makeNodeInvisible(node); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainHash] = nodesInGroup; _makeSchainNodesVisible(schainHash); } function _setException(bytes32 schainHash, uint nodeIndex) private { _exceptionsForGroups[schainHash][nodeIndex] = true; _nodeToLockedSchains[nodeIndex].push(schainHash); _schainToExceptionNodes[schainHash].push(nodeIndex); } function _makeSchainNodesVisible(bytes32 schainHash) private { INodes nodes = INodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) { nodes.makeNodeVisible(_schainToExceptionNodes[schainHash][i]); } } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainHash, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainHash]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: AGPL-3.0-only /* ISchainsInternal - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchainsInternal { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; uint generation; address originator; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } /** * @dev Emitted when schain type added. */ event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes); /** * @dev Emitted when schain type removed. */ event SchainTypeRemoved(uint indexed schainType); function initializeSchain( string calldata name, address from, address originator, uint lifetime, uint deposit) external; function createGroupForSchain( bytes32 schainHash, uint numberOfNodes, uint8 partOfNode ) external returns (uint[] memory); function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external; function removeSchain(bytes32 schainHash, address from) external; function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external; function deleteGroup(bytes32 schainHash) external; function setException(bytes32 schainHash, uint nodeIndex) external; function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external; function removeHolesForSchain(bytes32 schainHash) external; function addSchainType(uint8 partOfNode, uint numberOfNodes) external; function removeSchainType(uint typeOfSchain) external; function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external; function removeNodeFromAllExceptionSchains(uint nodeIndex) external; function removeAllNodesFromSchainExceptions(bytes32 schainHash) external; function makeSchainNodesInvisible(bytes32 schainHash) external; function makeSchainNodesVisible(bytes32 schainHash) external; function newGeneration() external; function addSchainForNode(uint nodeIndex, bytes32 schainHash) external; function removeSchainForNode(uint nodeIndex, uint schainIndex) external; function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external; function isSchainActive(bytes32 schainHash) external view returns (bool); function schainsAtSystem(uint index) external view returns (bytes32); function numberOfSchains() external view returns (uint64); function getSchains() external view returns (bytes32[] memory); function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8); function getSchainListSize(address from) external view returns (uint); function getSchainHashesByAddress(address from) external view returns (bytes32[] memory); function getSchainIdsByAddress(address from) external view returns (bytes32[] memory); function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainOwner(bytes32 schainHash) external view returns (address); function getSchainOriginator(bytes32 schainHash) external view returns (address); function isSchainNameAvailable(string calldata name) external view returns (bool); function isTimeExpired(bytes32 schainHash) external view returns (bool); function isOwnerAddress(address from, bytes32 schainId) external view returns (bool); function getSchainName(bytes32 schainHash) external view returns (string memory); function getActiveSchain(uint nodeIndex) external view returns (bytes32); function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains); function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint); function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory); function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool); function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint); function isAnyFreeNode(bytes32 schainHash) external view returns (bool); function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool); function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool); function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool); function getSchainType(uint typeOfSchain) external view returns(uint8, uint); function getGeneration(bytes32 schainHash) external view returns (uint); function isSchainExist(bytes32 schainHash) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISkaleDKG { struct Fp2Point { uint a; uint b; } struct G2Point { Fp2Point x; Fp2Point y; } struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; bool isResponse; bytes32 keyShare; G2Point sumOfVerVec; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } /** * @dev Emitted when a channel is opened. */ event ChannelOpened(bytes32 schainHash); /** * @dev Emitted when a channel is closed. */ event ChannelClosed(bytes32 schainHash); /** * @dev Emitted when a node broadcasts key share. */ event BroadcastAndKeyShare( bytes32 indexed schainHash, uint indexed fromNode, G2Point[] verificationVector, KeyShare[] secretKeyContribution ); /** * @dev Emitted when all group data is received by node. */ event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex); /** * @dev Emitted when DKG is successful. */ event SuccessfulDKG(bytes32 indexed schainHash); /** * @dev Emitted when a complaint against a node is verified. */ event BadGuy(uint nodeIndex); /** * @dev Emitted when DKG failed. */ event FailedDKG(bytes32 indexed schainHash); /** * @dev Emitted when a new node is rotated in. */ event NewGuy(uint nodeIndex); /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent(bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex); function alright(bytes32 schainHash, uint fromNodeIndex) external; function broadcast( bytes32 schainHash, uint nodeIndex, G2Point[] memory verificationVector, KeyShare[] memory secretKeyContribution ) external; function complaintBadData(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external; function preResponse( bytes32 schainId, uint fromNodeIndex, G2Point[] memory verificationVector, G2Point[] memory verificationVectorMultiplication, KeyShare[] memory secretKeyContribution ) external; function complaint(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external; function response( bytes32 schainHash, uint fromNodeIndex, uint secretNumber, G2Point memory multipliedShare ) external; function openChannel(bytes32 schainHash) external; function deleteChannel(bytes32 schainHash) external; function setStartAlrightTimestamp(bytes32 schainHash) external; function setBadNode(bytes32 schainHash, uint nodeIndex) external; function finalizeSlashing(bytes32 schainHash, uint badNode) external; function getChannelStartedTime(bytes32 schainHash) external view returns (uint); function getChannelStartedBlock(bytes32 schainHash) external view returns (uint); function getNumberOfBroadcasted(bytes32 schainHash) external view returns (uint); function getNumberOfCompleted(bytes32 schainHash) external view returns (uint); function getTimeOfLastSuccessfulDKG(bytes32 schainHash) external view returns (uint); function getComplaintData(bytes32 schainHash) external view returns (uint, uint); function getComplaintStartedTime(bytes32 schainHash) external view returns (uint); function getAlrightStartedTime(bytes32 schainHash) external view returns (uint); function isChannelOpened(bytes32 schainHash) external view returns (bool); function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); function isBroadcastPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isComplaintPossible( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool); function isAlrightPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isPreResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isNodeBroadcasted(bytes32 schainHash, uint nodeIndex) external view returns (bool); function isAllDataReceived(bytes32 schainHash, uint nodeIndex) external view returns (bool); function checkAndReturnIndexInGroup( bytes32 schainHash, uint nodeIndex, bool revertCheck ) external view returns (uint, bool); function isEveryoneBroadcasted(bytes32 schainHash) external view returns (bool); function hashData( KeyShare[] memory secretKeyContribution, G2Point[] memory verificationVector ) external pure returns (bytes32); } // SPDX-License-Identifier: AGPL-3.0-only /* INodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "./utils/IRandom.sol"; interface INodes { // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod ); /** * @dev Emitted when a node set to in compliant or compliant. */ event IncompliantNode( uint indexed nodeIndex, bool status ); /** * @dev Emitted when a node set to in maintenance or from in maintenance. */ event MaintenanceNode( uint indexed nodeIndex, bool status ); /** * @dev Emitted when a node status changed. */ event IPChanged( uint indexed nodeIndex, bytes4 previousIP, bytes4 newIP ); function removeSpaceFromNode(uint nodeIndex, uint8 space) external returns (bool); function addSpaceToNode(uint nodeIndex, uint8 space) external; function changeNodeLastRewardDate(uint nodeIndex) external; function changeNodeFinishTime(uint nodeIndex, uint time) external; function createNode(address from, NodeCreationParams calldata params) external; function initExit(uint nodeIndex) external; function completeExit(uint nodeIndex) external returns (bool); function deleteNodeForValidator(uint validatorId, uint nodeIndex) external; function checkPossibilityCreatingNode(address nodeAddress) external; function checkPossibilityToMaintainNode(uint validatorId, uint nodeIndex) external returns (bool); function setNodeInMaintenance(uint nodeIndex) external; function removeNodeFromInMaintenance(uint nodeIndex) external; function setNodeIncompliant(uint nodeIndex) external; function setNodeCompliant(uint nodeIndex) external; function setDomainName(uint nodeIndex, string memory domainName) external; function makeNodeVisible(uint nodeIndex) external; function makeNodeInvisible(uint nodeIndex) external; function changeIP(uint nodeIndex, bytes4 newIP, bytes4 newPublicIP) external; function numberOfActiveNodes() external view returns (uint); function incompliant(uint nodeIndex) external view returns (bool); function getRandomNodeWithFreeSpace( uint8 freeSpace, IRandom.RandomGenerator memory randomGenerator ) external view returns (uint); function isTimeForReward(uint nodeIndex) external view returns (bool); function getNodeIP(uint nodeIndex) external view returns (bytes4); function getNodeDomainName(uint nodeIndex) external view returns (string memory); function getNodePort(uint nodeIndex) external view returns (uint16); function getNodePublicKey(uint nodeIndex) external view returns (bytes32[2] memory); function getNodeAddress(uint nodeIndex) external view returns (address); function getNodeFinishTime(uint nodeIndex) external view returns (uint); function isNodeLeft(uint nodeIndex) external view returns (bool); function isNodeInMaintenance(uint nodeIndex) external view returns (bool); function getNodeLastRewardDate(uint nodeIndex) external view returns (uint); function getNodeNextRewardDate(uint nodeIndex) external view returns (uint); function getNumberOfNodes() external view returns (uint); function getNumberOnlineNodes() external view returns (uint); function getActiveNodeIds() external view returns (uint[] memory activeNodeIds); function getNodeStatus(uint nodeIndex) external view returns (NodeStatus); function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory); function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count); function getValidatorId(uint nodeIndex) external view returns (uint); function isNodeExist(address from, uint nodeIndex) external view returns (bool); function isNodeActive(uint nodeIndex) external view returns (bool); function isNodeLeaving(uint nodeIndex) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "@skalenetwork/skale-manager-interfaces/IPermissions.sol"; import "./thirdparty/openzeppelin/AccessControlUpgradeableLegacy.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeableLegacy, IPermissions { using AddressUpgradeable for address; IContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual override initializer { AccessControlUpgradeableLegacy.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeableLegacy skaleManager = AccessControlUpgradeableLegacy(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = IContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol"; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions, IConstantsHolder { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 134161; uint public constant BROADCAST_DELTA = 177490; uint public constant COMPLAINT_BAD_DATA_DELTA = 80995; uint public constant PRE_RESPONSE_DELTA = 100061; uint public constant COMPLAINT_DELTA = 104611; uint public constant RESPONSE_DELTA = 49132; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimeLimit; bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE"); modifier onlyConstantsHolderManager() { require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required"); _; } /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external override onlyConstantsHolderManager { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); emit ConstantUpdated( keccak256(abi.encodePacked("RewardPeriod")), uint(rewardPeriod), uint(newRewardPeriod) ); rewardPeriod = newRewardPeriod; emit ConstantUpdated( keccak256(abi.encodePacked("DeltaPeriod")), uint(deltaPeriod), uint(newDeltaPeriod) ); deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external override onlyConstantsHolderManager { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); emit ConstantUpdated( keccak256(abi.encodePacked("CheckTime")), uint(checkTime), uint(newCheckTime) ); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("AllowableLatency")), uint(allowableLatency), uint(newAllowableLatency) ); allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("MSR")), uint(msr), uint(newMSR) ); msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external override onlyConstantsHolderManager { require( block.timestamp < launchTimestamp, "Cannot set network launch timestamp because network is already launched" ); emit ConstantUpdated( keccak256(abi.encodePacked("LaunchTimestamp")), uint(launchTimestamp), uint(timestamp) ); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("RotationDelay")), uint(rotationDelay), uint(newDelay) ); rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("ProofOfUseLockUpPeriodDays")), uint(proofOfUseLockUpPeriodDays), uint(periodDays) ); proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external override onlyConstantsHolderManager { require(percentage <= 100, "Percentage value is incorrect"); emit ConstantUpdated( keccak256(abi.encodePacked("ProofOfUseDelegationPercentage")), uint(proofOfUseDelegationPercentage), uint(percentage) ); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("LimitValidatorsPerDelegator")), uint(limitValidatorsPerDelegator), uint(newLimit) ); limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("SchainCreationTimeStamp")), uint(schainCreationTimeStamp), uint(timestamp) ); schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("MinimalSchainLifetime")), uint(minimalSchainLifetime), uint(lifetime) ); minimalSchainLifetime = lifetime; } function setComplaintTimeLimit(uint timeLimit) external override onlyConstantsHolderManager { emit ConstantUpdated( keccak256(abi.encodePacked("ComplaintTimeLimit")), uint(complaintTimeLimit), uint(timeLimit) ); complaintTimeLimit = timeLimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = type(uint).max; rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimeLimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/utils/IRandom.sol"; /** * @title Random * @dev The library for generating of pseudo random numbers */ library Random { /** * @dev Create an instance of RandomGenerator */ function create(uint seed) internal pure returns (IRandom.RandomGenerator memory) { return IRandom.RandomGenerator({seed: seed}); } function createFromEntropy(bytes memory entropy) internal pure returns (IRandom.RandomGenerator memory) { return create(uint(keccak256(entropy))); } /** * @dev Generates random value */ function random(IRandom.RandomGenerator memory self) internal pure returns (uint) { self.seed = uint(sha256(abi.encodePacked(self.seed))); return self.seed; } /** * @dev Generates random value in range [0, max) */ function random(IRandom.RandomGenerator memory self, uint max) internal pure returns (uint) { assert(max > 0); uint maxRand = type(uint).max - type(uint).max % max; if (type(uint).max - maxRand == max - 1) { return random(self) % max; } else { uint rand = random(self); while (rand >= maxRand) { rand = random(self); } return rand % max; } } } // SPDX-License-Identifier: AGPL-3.0-only /* IRandom.sol - SKALE Manager Interfaces Copyright (C) 2022-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IRandom { struct RandomGenerator { uint seed; } } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external; function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function contracts(bytes32 nameHash) external view returns (address); function getDelegationPeriodManager() external view returns (address); function getBounty() external view returns (address); function getValidatorService() external view returns (address); function getTimeHelpers() external view returns (address); function getConstantsHolder() external view returns (address); function getSkaleToken() external view returns (address); function getTokenState() external view returns (address); function getPunisher() external view returns (address); function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* IPermissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IPermissions { function initialize(address contractManagerAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/thirdparty/openzeppelin/IAccessControlUpgradeableLegacy.sol"; import "./InitializableWithGap.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, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeableLegacy is InitializableWithGap, ContextUpgradeable, IAccessControlUpgradeableLegacy { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override 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 override 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 override 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 override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require(hasRole(_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 override { 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 override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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 // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* IAccessControlUpgradeableLegacy.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IAccessControlUpgradeableLegacy { /** * @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); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleAdmin(bytes32 role) external view returns (bytes32); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract InitializableWithGap is Initializable { uint256[50] private ______gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ 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() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library 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; 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 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: AGPL-3.0-only /* IConstantsHolder.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Artem Payvin SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IConstantsHolder { /** * @dev Emitted when constants updated. */ event ConstantUpdated( bytes32 indexed constantHash, uint previousValue, uint newValue ); function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external; function setCheckTime(uint newCheckTime) external; function setLatency(uint32 newAllowableLatency) external; function setMSR(uint newMSR) external; function setLaunchTimestamp(uint timestamp) external; function setRotationDelay(uint newDelay) external; function setProofOfUseLockUpPeriod(uint periodDays) external; function setProofOfUseDelegationPercentage(uint percentage) external; function setLimitValidatorsPerDelegator(uint newLimit) external; function setSchainCreationTimeStamp(uint timestamp) external; function setMinimalSchainLifetime(uint lifetime) external; function setComplaintTimeLimit(uint timeLimit) external; function msr() external view returns (uint); function launchTimestamp() external view returns (uint); function rotationDelay() external view returns (uint); function limitValidatorsPerDelegator() external view returns (uint); function schainCreationTimeStamp() external view returns (uint); function minimalSchainLifetime() external view returns (uint); function complaintTimeLimit() external view returns (uint); }
Allows Schains contract to remove an schain from the network. Generally schains are not removed from the system; instead they are simply allowed to expire. Requirements: - Message sender is Schains smart contract - Schain must exist/ TODO: optimize
function removeSchain(bytes32 schainHash, address from) external override allow("Schains") schainExists(schainHash) { isSchainActive[schainHash] = false; uint length = schainIndexes[from].length; uint index = schains[schainHash].indexInOwnerList; if (index != length - 1) { bytes32 lastSchainHash = schainIndexes[from][length - 1]; schains[lastSchainHash].indexInOwnerList = index; schainIndexes[from][index] = lastSchainHash; } schainIndexes[from].pop(); for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainHash) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length - 1]; break; } } schainsAtSystem.pop(); delete schains[schainHash]; numberOfSchains--; }
10,373,712
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.8.11; import "./Ownable.sol"; /** * @title Blocklistable Token * @dev Allows accounts to be blocklisted by a "blocklister" role */ contract Blocklistable is Ownable { address public blocklister; mapping(address => bool) internal blocklisted; event Blocklisted(address indexed _account); event UnBlocklisted(address indexed _account); event BlocklisterChanged(address indexed newBlocklister); /** * @dev Throws if called by any account other than the blocklister */ modifier onlyBlocklister() { require( msg.sender == blocklister, "Blocklistable: caller is not the blocklister" ); _; } /** * @dev Throws if argument account is blocklisted * @param _account The address to check */ modifier notBlocklisted(address _account) { require( !blocklisted[_account], "Blocklistable: account is blocklisted" ); _; } /** * @dev Checks if account is blocklisted * @param _account The address to check */ function isBlocklisted(address _account) external view returns (bool) { return blocklisted[_account]; } /** * @dev Adds account to blocklist * @param _account The address to blocklist */ function blocklist(address _account) external onlyBlocklister { blocklisted[_account] = true; emit Blocklisted(_account); } /** * @dev Removes account from blocklist * @param _account The address to remove from the blocklist */ function unBlocklist(address _account) external onlyBlocklister { blocklisted[_account] = false; emit UnBlocklisted(_account); } function updateBlocklister(address _newBlocklister) external onlyOwner { require( _newBlocklister != address(0), "Blocklistable: new blocklister is the zero address" ); blocklister = _newBlocklister; emit BlocklisterChanged(blocklister); } uint256[50] private __gap; }
Adds account to blocklist _account The address to blocklist/
function blocklist(address _account) external onlyBlocklister { blocklisted[_account] = true; emit Blocklisted(_account); }
15,802,748
./full_match/1/0xA5D49e646398C6c023db7A4b94805d7A07B8F4a6/sources/contracts/blindBackrun.sol
Executes a call to another contract with the provided data and value. Only the contract owner can call this function. Reverted calls will result in a revert. _to The address of the contract to call. _value The amount of Ether to send with the call. _data The calldata to send with the call.
function call( address payable _to, uint256 _value, bytes memory _data ) external onlyOwner { require(success, "External call failed"); }
2,921,889
// SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; import {IPremiaOptionNFTDisplay} from "../interface/IPremiaOptionNFTDisplay.sol"; import {IPoolView, IERC1155Metadata} from "./IPoolView.sol"; import {PoolInternal} from "./PoolInternal.sol"; import {PoolStorage} from "./PoolStorage.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolView is IPoolView, PoolInternal { using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; address internal immutable NFT_DISPLAY_ADDRESS; constructor( address nftDisplay, address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 feePremium64x64, int128 feeApy64x64 ) PoolInternal( ivolOracle, weth, premiaMining, feeReceiver, feeDiscountAddress, feePremium64x64, feeApy64x64 ) { NFT_DISPLAY_ADDRESS = nftDisplay; } /** * @inheritdoc IPoolView */ function getFeeReceiverAddress() external view returns (address) { return FEE_RECEIVER_ADDRESS; } /** * @inheritdoc IPoolView */ function getPoolSettings() external view returns (PoolStorage.PoolSettings memory) { PoolStorage.Layout storage l = PoolStorage.layout(); return PoolStorage.PoolSettings( l.underlying, l.base, l.underlyingOracle, l.baseOracle ); } /** * @inheritdoc IPoolView */ function getTokenIds() external view returns (uint256[] memory) { PoolStorage.Layout storage l = PoolStorage.layout(); uint256 length = l.tokenIds.length(); uint256[] memory result = new uint256[](length); for (uint256 i = 0; i < length; i++) { result[i] = l.tokenIds.at(i); } return result; } /** * @inheritdoc IPoolView */ function getCLevel64x64(bool isCall) external view returns (int128 cLevel64x64) { (cLevel64x64, ) = PoolStorage.layout().getRealPoolState(isCall); } /** * @inheritdoc IPoolView */ function getSteepness64x64(bool isCallPool) external view returns (int128) { if (isCallPool) { return PoolStorage.layout().steepnessUnderlying64x64; } else { return PoolStorage.layout().steepnessBase64x64; } } /** * @inheritdoc IPoolView */ function getPrice64x64(uint256 timestamp) external view returns (int128) { return PoolStorage.layout().getPriceUpdate(timestamp); } /** * @inheritdoc IPoolView */ function getPriceAfter64x64(uint256 timestamp) external view returns (int128 spot64x64) { PoolStorage.Layout storage l = PoolStorage.layout(); spot64x64 = l.getPriceUpdateAfter(timestamp); if (spot64x64 == 0) { spot64x64 = l.fetchPriceUpdate(); } } /** * @inheritdoc IPoolView */ function getParametersForTokenId(uint256 tokenId) external pure returns ( PoolStorage.TokenType, uint64, int128 ) { return PoolStorage.parseTokenId(tokenId); } /** * @inheritdoc IPoolView */ function getMinimumAmounts() external view returns (uint256 minCallTokenAmount, uint256 minPutTokenAmount) { PoolStorage.Layout storage l = PoolStorage.layout(); return (l.getMinimumAmount(true), l.getMinimumAmount(false)); } /** * @inheritdoc IPoolView */ function getUserTVL(address user) external view returns (uint256 underlyingTVL, uint256 baseTVL) { PoolStorage.Layout storage l = PoolStorage.layout(); return (l.userTVL[user][true], l.userTVL[user][false]); } /** * @inheritdoc IPoolView */ function getTotalTVL() external view returns (uint256 underlyingTVL, uint256 baseTVL) { PoolStorage.Layout storage l = PoolStorage.layout(); return (l.totalTVL[true], l.totalTVL[false]); } /** * @inheritdoc IPoolView */ function getLiquidityQueuePosition(address account, bool isCallPool) external view returns (uint256 liquidityBeforePosition, uint256 positionSize) { PoolStorage.Layout storage l = PoolStorage.layout(); uint256 tokenId = _getFreeLiquidityTokenId(isCallPool); if (!l.isInQueue(account, isCallPool)) { liquidityBeforePosition = _totalSupply(tokenId); } else { mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; address depositor = asc[address(0)]; while (depositor != account) { liquidityBeforePosition += _balanceOf(depositor, tokenId); depositor = asc[depositor]; } positionSize = _balanceOf(depositor, tokenId); } } /** * @inheritdoc IPoolView */ function getPremiaMining() external view returns (address) { return PREMIA_MINING_ADDRESS; } /** * @inheritdoc IPoolView */ function getDivestmentTimestamps(address account) external view returns ( uint256 callDivestmentTimestamp, uint256 putDivestmentTimestamp ) { PoolStorage.Layout storage l = PoolStorage.layout(); callDivestmentTimestamp = l.divestmentTimestamps[account][true]; putDivestmentTimestamp = l.divestmentTimestamps[account][false]; } /** * @inheritdoc IPoolView */ function getFeesReserved(address account, uint256 shortTokenId) external view returns (uint256 feesReserved) { feesReserved = PoolStorage.layout().feesReserved[account][shortTokenId]; } /** * @inheritdoc IERC1155Metadata * @dev SVG generated via external PremiaOptionNFTDisplay contract */ function uri(uint256 tokenId) external view returns (string memory) { return IPremiaOptionNFTDisplay(NFT_DISPLAY_ADDRESS).tokenURI( address(this), tokenId ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Set implementation with enumeration functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license) */ library EnumerableSet { struct Set { bytes32[] _values; // 1-indexed to allow 0 to signify nonexistence mapping(bytes32 => uint256) _indexes; } struct Bytes32Set { Set _inner; } struct AddressSet { Set _inner; } struct UintSet { Set _inner; } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function indexOf(Bytes32Set storage set, bytes32 value) internal view returns (uint256) { return _indexOf(set._inner, value); } function indexOf(AddressSet storage set, address value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(uint256(uint160(value)))); } function indexOf(UintSet storage set, uint256 value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(value)); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, 'EnumerableSet: index out of bounds' ); return set._values[index]; } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _indexOf(Set storage set, bytes32 value) private view returns (uint256) { unchecked { return set._indexes[value] - 1; } } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { unchecked { bytes32 last = set._values[set._values.length - 1]; // move last value to now-vacant index set._values[valueIndex - 1] = last; set._indexes[last] = valueIndex; } // clear last index set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; interface IPremiaOptionNFTDisplay { function tokenURI(address _pool, uint256 _tokenId) external view returns (string memory); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {IERC1155Metadata} from "@solidstate/contracts/token/ERC1155/metadata/IERC1155Metadata.sol"; import {PoolStorage} from "./PoolStorage.sol"; /** * @notice Pool view function interface */ interface IPoolView is IERC1155Metadata { /** * @notice get fee receiver address * @dev called by PremiaMakerKeeper * @return fee receiver address */ function getFeeReceiverAddress() external view returns (address); /** * @notice get fundamental pool attributes * @return structured PoolSettings */ function getPoolSettings() external view returns (PoolStorage.PoolSettings memory); /** * @notice get the list of all token ids in circulation * @return list of token ids */ function getTokenIds() external view returns (uint256[] memory); /** * @notice get current C-Level, accounting for unrealized decay and pending deposits * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getCLevel64x64(bool isCall) external view returns (int128); /** * @notice get steepness coefficient * @param isCall whether query is for call or put pool * @return 64x64 fixed point representation of C steepness of Pool */ function getSteepness64x64(bool isCall) external view returns (int128); /** * @notice get oracle price at timestamp * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPrice64x64(uint256 timestamp) external view returns (int128); /** * @notice get first oracle price update after timestamp. If no update has been registered yet, return current price feed spot price * @param timestamp timestamp to query * @return spot64x64 64x64 fixed point representation of price */ function getPriceAfter64x64(uint256 timestamp) external view returns (int128 spot64x64); /** * @notice get parameters for token id * @param tokenId token id to query * @return token type enum * @return maturity * @return 64x64 fixed point representation of strike price */ function getParametersForTokenId(uint256 tokenId) external pure returns ( PoolStorage.TokenType, uint64, int128 ); /** * @notice get minimum purchase and interval amounts * @return minCallTokenAmount minimum call pool amount * @return minPutTokenAmount minimum put pool amount */ function getMinimumAmounts() external view returns (uint256 minCallTokenAmount, uint256 minPutTokenAmount); /** * @notice get TVL (total value locked) for given address * @param account address whose TVL to query * @return underlyingTVL user total value locked in call pool (in underlying token amount) * @return baseTVL user total value locked in put pool (in base token amount) */ function getUserTVL(address account) external view returns (uint256 underlyingTVL, uint256 baseTVL); /** * @notice get TVL (total value locked) of entire Pool * @return underlyingTVL total value locked in call pool (in underlying token amount) * @return baseTVL total value locked in put pool (in base token amount) */ function getTotalTVL() external view returns (uint256 underlyingTVL, uint256 baseTVL); /** * @notice get position in the liquidity queue of the Pool * @param account account address whose liquidity position to query * @param isCallPool whether query is for call or put pool * @return liquidityBeforePosition total available liquidity before account's liquidity queue * @return positionSize size of the account's liquidity queue position */ function getLiquidityQueuePosition(address account, bool isCallPool) external view returns (uint256 liquidityBeforePosition, uint256 positionSize); /** * @notice get the amount of APY fees reserved for given user and token id * @param account account whose reserved fees to query * @param shortTokenId short token id whose reserved fees to query * @return amount quantity of fees reserved */ function getFeesReserved(address account, uint256 shortTokenId) external view returns (uint256 amount); /** * @notice get the address of PremiaMining contract * @return address of PremiaMining contract */ function getPremiaMining() external view returns (address); /** * @notice get the gradual divestment timestamps of a user * @param account address whose divestment timestamps to query * @return callDivestmentTimestamp gradual divestment timestamp of the user for the call pool * @return putDivestmentTimestamp gradual divestment timestamp of the user for the put pool */ function getDivestmentTimestamps(address account) external view returns ( uint256 callDivestmentTimestamp, uint256 putDivestmentTimestamp ); } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {IERC173} from "@solidstate/contracts/access/IERC173.sol"; import {OwnableStorage} from "@solidstate/contracts/access/OwnableStorage.sol"; import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol"; import {ERC1155EnumerableInternal, ERC1155EnumerableStorage, EnumerableSet} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol"; import {IWETH} from "@solidstate/contracts/utils/IWETH.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; import {IFeeDiscount} from "../staking/IFeeDiscount.sol"; import {IPoolEvents} from "./IPoolEvents.sol"; import {IPremiaMining} from "../mining/IPremiaMining.sol"; import {IVolatilitySurfaceOracle} from "../oracle/IVolatilitySurfaceOracle.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolInternal is IPoolEvents, ERC1155EnumerableInternal { using ABDKMath64x64 for int128; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; struct Interval { uint256 contractSize; uint256 tokenAmount; uint256 payment; uint256 apyFee; } address internal immutable WETH_ADDRESS; address internal immutable PREMIA_MINING_ADDRESS; address internal immutable FEE_RECEIVER_ADDRESS; address internal immutable FEE_DISCOUNT_ADDRESS; address internal immutable IVOL_ORACLE_ADDRESS; int128 internal immutable FEE_PREMIUM_64x64; int128 internal immutable FEE_APY_64x64; uint256 internal immutable UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 internal immutable BASE_FREE_LIQ_TOKEN_ID; uint256 internal immutable UNDERLYING_RESERVED_LIQ_TOKEN_ID; uint256 internal immutable BASE_RESERVED_LIQ_TOKEN_ID; uint256 internal constant INVERSE_BASIS_POINT = 1e4; uint256 internal constant BATCHING_PERIOD = 260; // Minimum APY for capital locked up to underwrite options. // The quote will return a minimum price corresponding to this APY int128 internal constant MIN_APY_64x64 = 0x4ccccccccccccccd; // 0.3 // Multiply sell quote by this constant int128 internal constant SELL_COEFFICIENT_64x64 = 0xb333333333333333; // 0.7 constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 feePremium64x64, int128 feeApy64x64 ) { IVOL_ORACLE_ADDRESS = ivolOracle; WETH_ADDRESS = weth; PREMIA_MINING_ADDRESS = premiaMining; FEE_RECEIVER_ADDRESS = feeReceiver; // PremiaFeeDiscount contract address FEE_DISCOUNT_ADDRESS = feeDiscountAddress; FEE_PREMIUM_64x64 = feePremium64x64; FEE_APY_64x64 = feeApy64x64; UNDERLYING_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_FREE_LIQ, 0, 0 ); BASE_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_FREE_LIQ, 0, 0 ); UNDERLYING_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_RESERVED_LIQ, 0, 0 ); BASE_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_RESERVED_LIQ, 0, 0 ); } modifier onlyProtocolOwner() { require( msg.sender == IERC173(OwnableStorage.layout().owner).owner(), "Not protocol owner" ); _; } function _fetchFeeDiscount64x64(address feePayer) internal view returns (int128 discount64x64) { if (FEE_DISCOUNT_ADDRESS != address(0)) { discount64x64 = ABDKMath64x64.divu( IFeeDiscount(FEE_DISCOUNT_ADDRESS).getDiscount(feePayer), INVERSE_BASIS_POINT ); } } function _withdrawFees(bool isCall) internal returns (uint256 amount) { uint256 tokenId = _getReservedLiquidityTokenId(isCall); amount = _balanceOf(FEE_RECEIVER_ADDRESS, tokenId); if (amount > 0) { _burn(FEE_RECEIVER_ADDRESS, tokenId, amount); _pushTo( FEE_RECEIVER_ADDRESS, PoolStorage.layout().getPoolToken(isCall), amount ); emit FeeWithdrawal(isCall, amount); } } /** * @notice calculate price of option contract * @param args structured quote arguments * @return result quote result */ function _quotePurchasePrice(PoolStorage.QuoteArgsInternal memory args) internal view returns (PoolStorage.QuoteResultInternal memory result) { require( args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0, "invalid args" ); PoolStorage.Layout storage l = PoolStorage.layout(); int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( args.contractSize, l.underlyingDecimals ); (int128 adjustedCLevel64x64, int128 oldLiquidity64x64) = l .getRealPoolState(args.isCall); require(oldLiquidity64x64 > 0, "no liq"); int128 timeToMaturity64x64 = ABDKMath64x64.divu( args.maturity - block.timestamp, 365 days ); int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle( IVOL_ORACLE_ADDRESS ).getAnnualizedVolatility64x64( l.base, l.underlying, args.spot64x64, args.strike64x64, timeToMaturity64x64 ); require(annualizedVolatility64x64 > 0, "vol = 0"); int128 collateral64x64 = args.isCall ? contractSize64x64 : contractSize64x64.mul(args.strike64x64); ( int128 price64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) = OptionMath.quotePrice( OptionMath.QuoteArgs( annualizedVolatility64x64.mul(annualizedVolatility64x64), args.strike64x64, args.spot64x64, timeToMaturity64x64, adjustedCLevel64x64, oldLiquidity64x64, oldLiquidity64x64.sub(collateral64x64), 0x10000000000000000, // 64x64 fixed point representation of 1 MIN_APY_64x64, args.isCall ) ); result.baseCost64x64 = args.isCall ? price64x64.mul(contractSize64x64).div(args.spot64x64) : price64x64.mul(contractSize64x64); result.feeCost64x64 = result.baseCost64x64.mul(FEE_PREMIUM_64x64); result.cLevel64x64 = cLevel64x64; result.slippageCoefficient64x64 = slippageCoefficient64x64; result.feeCost64x64 -= result.feeCost64x64.mul( _fetchFeeDiscount64x64(args.feePayer) ); } function _quoteSalePrice(PoolStorage.QuoteArgsInternal memory args) internal view returns (int128 baseCost64x64, int128 feeCost64x64) { require( args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0, "invalid args" ); PoolStorage.Layout storage l = PoolStorage.layout(); int128 timeToMaturity64x64 = ABDKMath64x64.divu( args.maturity - block.timestamp, 365 days ); int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle( IVOL_ORACLE_ADDRESS ).getAnnualizedVolatility64x64( l.base, l.underlying, args.spot64x64, args.strike64x64, timeToMaturity64x64 ); require(annualizedVolatility64x64 > 0, "vol = 0"); int128 blackScholesPrice64x64 = OptionMath._blackScholesPrice( annualizedVolatility64x64.mul(annualizedVolatility64x64), args.strike64x64, args.spot64x64, timeToMaturity64x64, args.isCall ); int128 exerciseValue64x64 = ABDKMath64x64Token.fromDecimals( _calculateExerciseValue( l, args.contractSize, args.spot64x64, args.strike64x64, args.isCall ), l.baseDecimals ); int128 sellCLevel64x64; { uint256 longTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(args.isCall, true), args.maturity, args.strike64x64 ); // Initialize to avg value, and replace by current if avg not set or current is lower sellCLevel64x64 = l.avgCLevel64x64[longTokenId]; { (int128 currentCLevel64x64, ) = l.getRealPoolState(args.isCall); if ( sellCLevel64x64 == 0 || currentCLevel64x64 < sellCLevel64x64 ) { sellCLevel64x64 = currentCLevel64x64; } } } int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( args.contractSize, l.underlyingDecimals ); baseCost64x64 = SELL_COEFFICIENT_64x64 .mul(sellCLevel64x64) .mul( blackScholesPrice64x64.mul(contractSize64x64).sub( exerciseValue64x64 ) ) .add(exerciseValue64x64); if (args.isCall) { baseCost64x64 = baseCost64x64.div(args.spot64x64); } feeCost64x64 = baseCost64x64.mul(FEE_PREMIUM_64x64); feeCost64x64 -= feeCost64x64.mul(_fetchFeeDiscount64x64(args.feePayer)); baseCost64x64 -= feeCost64x64; } function _getAvailableBuybackLiquidity(uint256 shortTokenId) internal view returns (uint256 totalLiquidity) { PoolStorage.Layout storage l = PoolStorage.layout(); EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage .layout() .accountsByToken[shortTokenId]; (PoolStorage.TokenType tokenType, , ) = PoolStorage.parseTokenId( shortTokenId ); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL; uint256 length = accounts.length(); for (uint256 i = 0; i < length; i++) { address lp = accounts.at(i); if (l.isBuybackEnabled[lp][isCall]) { totalLiquidity += _balanceOf(lp, shortTokenId); } } } /** * @notice burn corresponding long and short option tokens * @param l storage layout struct * @param account holder of tokens to annihilate * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to annihilate * @return collateralFreed amount of collateral freed, including APY fee rebate */ function _annihilate( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize ) internal returns (uint256 collateralFreed) { uint256 longTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, true), maturity, strike64x64 ); uint256 shortTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, false), maturity, strike64x64 ); uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); // calculate unconsumed APY fee so that it may be refunded uint256 intervalApyFee = _calculateApyFee( l, shortTokenId, tokenAmount, maturity ); _burn(account, longTokenId, contractSize); uint256 rebate = _fulfillApyFee( l, account, shortTokenId, contractSize, intervalApyFee, isCall ); _burn(account, shortTokenId, contractSize); collateralFreed = tokenAmount + rebate + intervalApyFee; emit Annihilate(shortTokenId, contractSize); } /** * @notice deposit underlying currency, underwriting calls of that currency with respect to base currency * @param amount quantity of underlying currency to deposit * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @param creditMessageValue whether to apply message value as credit towards transfer */ function _deposit( uint256 amount, bool isCallPool, bool creditMessageValue ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); // Reset gradual divestment timestamp delete l.divestmentTimestamps[msg.sender][isCallPool]; _processPendingDeposits(l, isCallPool); l.depositedAt[msg.sender][isCallPool] = block.timestamp; _addUserTVL(l, msg.sender, isCallPool, amount); _pullFrom(l, msg.sender, amount, isCallPool, creditMessageValue); _addToDepositQueue(msg.sender, amount, isCallPool); emit Deposit(msg.sender, isCallPool, amount); } /** * @notice purchase option * @param l storage layout struct * @param account recipient of purchased option * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize size of option contract * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to purchase long position * @return feeCost quantity of tokens required to pay fees */ function _purchase( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns (uint256 baseCost, uint256 feeCost) { require(maturity > block.timestamp, "expired"); require(contractSize >= l.underlyingMinimum, "too small"); { uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); uint256 freeLiquidityTokenId = _getFreeLiquidityTokenId(isCall); require( tokenAmount <= _totalSupply(freeLiquidityTokenId) - l.totalPendingDeposits(isCall) - (_balanceOf(account, freeLiquidityTokenId) - l.pendingDepositsOf(account, isCall)), "insuf liq" ); } PoolStorage.QuoteResultInternal memory quote = _quotePurchasePrice( PoolStorage.QuoteArgsInternal( account, maturity, strike64x64, newPrice64x64, contractSize, isCall ) ); baseCost = ABDKMath64x64Token.toDecimals( quote.baseCost64x64, l.getTokenDecimals(isCall) ); feeCost = ABDKMath64x64Token.toDecimals( quote.feeCost64x64, l.getTokenDecimals(isCall) ); uint256 longTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, true), maturity, strike64x64 ); _updateCLevelAverage(l, longTokenId, contractSize, quote.cLevel64x64); // mint long option token for buyer _mint(account, longTokenId, contractSize); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); // burn free liquidity tokens from other underwriters _mintShortTokenLoop( l, account, maturity, strike64x64, contractSize, baseCost, isCall ); int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCall); // mint reserved liquidity tokens for fee receiver _processAvailableFunds( FEE_RECEIVER_ADDRESS, feeCost, isCall, true, false ); emit Purchase( account, longTokenId, contractSize, baseCost, feeCost, newPrice64x64 ); } /** * @notice reassign short position to new underwriter * @param l storage layout struct * @param account holder of positions to be reassigned * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to reassign * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to reassign short position * @return feeCost quantity of tokens required to pay fees * @return netCollateralFreed quantity of liquidity freed */ function _reassign( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns ( uint256 baseCost, uint256 feeCost, uint256 netCollateralFreed ) { (baseCost, feeCost) = _purchase( l, account, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); uint256 totalCollateralFreed = _annihilate( l, account, maturity, strike64x64, isCall, contractSize ); netCollateralFreed = totalCollateralFreed - baseCost - feeCost; } /** * @notice exercise option on behalf of holder * @dev used for processing of expired options if passed holder is zero address * @param holder owner of long option tokens to exercise * @param longTokenId long option token id * @param contractSize quantity of tokens to exercise */ function _exercise( address holder, uint256 longTokenId, uint256 contractSize ) internal { uint64 maturity; int128 strike64x64; bool isCall; bool onlyExpired = holder == address(0); { PoolStorage.TokenType tokenType; (tokenType, maturity, strike64x64) = PoolStorage.parseTokenId( longTokenId ); require( tokenType == PoolStorage.TokenType.LONG_CALL || tokenType == PoolStorage.TokenType.LONG_PUT, "invalid type" ); require(!onlyExpired || maturity < block.timestamp, "not expired"); isCall = tokenType == PoolStorage.TokenType.LONG_CALL; } PoolStorage.Layout storage l = PoolStorage.layout(); int128 spot64x64 = _update(l); if (maturity < block.timestamp) { spot64x64 = l.getPriceUpdateAfter(maturity); } require( onlyExpired || ( isCall ? (spot64x64 > strike64x64) : (spot64x64 < strike64x64) ), "not ITM" ); uint256 exerciseValue = _calculateExerciseValue( l, contractSize, spot64x64, strike64x64, isCall ); if (onlyExpired) { // burn long option tokens from multiple holders // transfer profit to and emit Exercise event for each holder in loop _burnLongTokenLoop( contractSize, exerciseValue, longTokenId, isCall ); } else { // burn long option tokens from sender _burnLongTokenInterval( holder, longTokenId, contractSize, exerciseValue, isCall ); } // burn short option tokens from multiple underwriters _burnShortTokenLoop( l, maturity, strike64x64, contractSize, exerciseValue, isCall, false ); } function _calculateExerciseValue( PoolStorage.Layout storage l, uint256 contractSize, int128 spot64x64, int128 strike64x64, bool isCall ) internal view returns (uint256 exerciseValue) { // calculate exercise value if option is in-the-money if (isCall) { if (spot64x64 > strike64x64) { exerciseValue = spot64x64.sub(strike64x64).div(spot64x64).mulu( contractSize ); } } else { if (spot64x64 < strike64x64) { exerciseValue = l.contractSizeToBaseTokenAmount( contractSize, strike64x64.sub(spot64x64), false ); } } } function _mintShortTokenLoop( PoolStorage.Layout storage l, address buyer, uint64 maturity, int128 strike64x64, uint256 contractSize, uint256 premium, bool isCall ) internal { uint256 shortTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, false), maturity, strike64x64 ); uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); // calculate anticipated APY fee so that it may be reserved uint256 apyFee = _calculateApyFee( l, shortTokenId, tokenAmount, maturity ); while (tokenAmount > 0) { address underwriter = l.liquidityQueueAscending[isCall][address(0)]; uint256 balance = _balanceOf( underwriter, _getFreeLiquidityTokenId(isCall) ); // if underwriter is in process of divestment, remove from queue if (!l.getReinvestmentStatus(underwriter, isCall)) { _burn(underwriter, _getFreeLiquidityTokenId(isCall), balance); _processAvailableFunds( underwriter, balance, isCall, true, false ); _subUserTVL(l, underwriter, isCall, balance); continue; } // if underwriter has insufficient liquidity, remove from queue if (balance < l.getMinimumAmount(isCall)) { l.removeUnderwriter(underwriter, isCall); continue; } // move interval to end of queue if underwriter is buyer if (underwriter == buyer) { l.removeUnderwriter(underwriter, isCall); l.addUnderwriter(underwriter, isCall); continue; } balance -= l.pendingDepositsOf(underwriter, isCall); Interval memory interval; // amount of liquidity provided by underwriter, accounting for reinvested premium interval.tokenAmount = (balance * (tokenAmount + premium - apyFee)) / tokenAmount; // skip underwriters whose liquidity is pending deposit processing if (interval.tokenAmount == 0) continue; // truncate interval if underwriter has excess liquidity available if (interval.tokenAmount > tokenAmount) interval.tokenAmount = tokenAmount; // calculate derived interval variables interval.contractSize = (contractSize * interval.tokenAmount) / tokenAmount; interval.payment = (premium * interval.tokenAmount) / tokenAmount; interval.apyFee = (apyFee * interval.tokenAmount) / tokenAmount; _mintShortTokenInterval( l, underwriter, buyer, shortTokenId, interval, isCall ); tokenAmount -= interval.tokenAmount; contractSize -= interval.contractSize; premium -= interval.payment; apyFee -= interval.apyFee; } } function _mintShortTokenInterval( PoolStorage.Layout storage l, address underwriter, address longReceiver, uint256 shortTokenId, Interval memory interval, bool isCallPool ) internal { // track prepaid APY fees _reserveApyFee(l, underwriter, shortTokenId, interval.apyFee); // if payment is equal to collateral amount plus APY fee, this is a manual underwrite bool isManualUnderwrite = interval.payment == interval.tokenAmount + interval.apyFee; if (!isManualUnderwrite) { // burn free liquidity tokens from underwriter _burn( underwriter, _getFreeLiquidityTokenId(isCallPool), interval.tokenAmount + interval.apyFee - interval.payment ); } // mint short option tokens for underwriter _mint(underwriter, shortTokenId, interval.contractSize); _addUserTVL( l, underwriter, isCallPool, interval.payment - interval.apyFee ); emit Underwrite( underwriter, longReceiver, shortTokenId, interval.contractSize, isManualUnderwrite ? 0 : interval.payment, isManualUnderwrite ); } function _burnLongTokenLoop( uint256 contractSize, uint256 exerciseValue, uint256 longTokenId, bool isCallPool ) internal { EnumerableSet.AddressSet storage holders = ERC1155EnumerableStorage .layout() .accountsByToken[longTokenId]; while (contractSize > 0) { address longTokenHolder = holders.at(holders.length() - 1); uint256 intervalContractSize = _balanceOf( longTokenHolder, longTokenId ); // truncate interval if holder has excess long position size if (intervalContractSize > contractSize) intervalContractSize = contractSize; uint256 intervalExerciseValue = (exerciseValue * intervalContractSize) / contractSize; _burnLongTokenInterval( longTokenHolder, longTokenId, intervalContractSize, intervalExerciseValue, isCallPool ); contractSize -= intervalContractSize; exerciseValue -= intervalExerciseValue; } } function _burnLongTokenInterval( address holder, uint256 longTokenId, uint256 contractSize, uint256 exerciseValue, bool isCallPool ) internal { _burn(holder, longTokenId, contractSize); if (exerciseValue > 0) { _processAvailableFunds( holder, exerciseValue, isCallPool, true, true ); } emit Exercise(holder, longTokenId, contractSize, exerciseValue, 0); } function _burnShortTokenLoop( PoolStorage.Layout storage l, uint64 maturity, int128 strike64x64, uint256 contractSize, uint256 payment, bool isCall, bool onlyBuybackLiquidity ) internal { uint256 shortTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, false), maturity, strike64x64 ); uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); // calculate unconsumed APY fee so that it may be refunded uint256 apyFee = _calculateApyFee( l, shortTokenId, tokenAmount, maturity ); EnumerableSet.AddressSet storage underwriters = ERC1155EnumerableStorage .layout() .accountsByToken[shortTokenId]; uint256 index = underwriters.length(); while (contractSize > 0) { address underwriter = underwriters.at(--index); // skip underwriters who do not provide buyback liqudity, if applicable if ( onlyBuybackLiquidity && !l.isBuybackEnabled[underwriter][isCall] ) continue; Interval memory interval; // amount of liquidity provided by underwriter interval.contractSize = _balanceOf(underwriter, shortTokenId); // truncate interval if underwriter has excess short position size if (interval.contractSize > contractSize) interval.contractSize = contractSize; // calculate derived interval variables interval.tokenAmount = (tokenAmount * interval.contractSize) / contractSize; interval.payment = (payment * interval.contractSize) / contractSize; interval.apyFee = (apyFee * interval.contractSize) / contractSize; _burnShortTokenInterval( l, underwriter, shortTokenId, interval, isCall, onlyBuybackLiquidity ); contractSize -= interval.contractSize; tokenAmount -= interval.tokenAmount; payment -= interval.payment; apyFee -= interval.apyFee; } } function _burnShortTokenInterval( PoolStorage.Layout storage l, address underwriter, uint256 shortTokenId, Interval memory interval, bool isCallPool, bool isSale ) internal { // track prepaid APY fees uint256 refundWithRebate = interval.apyFee + _fulfillApyFee( l, underwriter, shortTokenId, interval.contractSize, interval.apyFee, isCallPool ); // burn short option tokens from underwriter _burn(underwriter, shortTokenId, interval.contractSize); bool divest = !l.getReinvestmentStatus(underwriter, isCallPool); _processAvailableFunds( underwriter, interval.tokenAmount - interval.payment + refundWithRebate, isCallPool, divest, false ); if (divest) { _subUserTVL(l, underwriter, isCallPool, interval.tokenAmount); } else { if (refundWithRebate > interval.payment) { _addUserTVL( l, underwriter, isCallPool, refundWithRebate - interval.payment ); } else if (interval.payment > refundWithRebate) { _subUserTVL( l, underwriter, isCallPool, interval.payment - refundWithRebate ); } } if (isSale) { emit AssignSale( underwriter, shortTokenId, interval.tokenAmount - interval.payment, interval.contractSize ); } else { emit AssignExercise( underwriter, shortTokenId, interval.tokenAmount - interval.payment, interval.contractSize, 0 ); } } function _calculateApyFee( PoolStorage.Layout storage l, uint256 shortTokenId, uint256 tokenAmount, uint64 maturity ) internal view returns (uint256 apyFee) { if (block.timestamp < maturity) { int128 apyFeeRate64x64 = _totalSupply(shortTokenId) == 0 ? FEE_APY_64x64 : l.feeReserveRates[shortTokenId]; apyFee = apyFeeRate64x64.mulu( (tokenAmount * (maturity - block.timestamp)) / (365 days) ); } } function _reserveApyFee( PoolStorage.Layout storage l, address underwriter, uint256 shortTokenId, uint256 amount ) internal { l.feesReserved[underwriter][shortTokenId] += amount; emit APYFeeReserved(underwriter, shortTokenId, amount); } /** * @notice credit fee receiver with fees earned and calculate rebate for underwriter * @dev short tokens which have acrrued fee must not be burned or transferred until after this helper is called * @param l storage layout struct * @param underwriter holder of short position who reserved fees * @param shortTokenId short token id whose reserved fees to pay and rebate * @param intervalContractSize size of position for which to calculate accrued fees * @param intervalApyFee quantity of fees reserved but not yet accrued * @param isCallPool true for call, false for put */ function _fulfillApyFee( PoolStorage.Layout storage l, address underwriter, uint256 shortTokenId, uint256 intervalContractSize, uint256 intervalApyFee, bool isCallPool ) internal returns (uint256 rebate) { if (intervalApyFee == 0) return 0; // calculate proportion of fees reserved corresponding to interval uint256 feesReserved = l.feesReserved[underwriter][shortTokenId]; uint256 intervalFeesReserved = (feesReserved * intervalContractSize) / _balanceOf(underwriter, shortTokenId); // deduct fees for time not elapsed l.feesReserved[underwriter][shortTokenId] -= intervalFeesReserved; // apply rebate to fees accrued rebate = _fetchFeeDiscount64x64(underwriter).mulu( intervalFeesReserved - intervalApyFee ); // credit fee receiver with fees paid uint256 intervalFeesPaid = intervalFeesReserved - intervalApyFee - rebate; _processAvailableFunds( FEE_RECEIVER_ADDRESS, intervalFeesPaid, isCallPool, true, false ); emit APYFeePaid(underwriter, shortTokenId, intervalFeesPaid); } function _addToDepositQueue( address account, uint256 amount, bool isCallPool ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); _mint(account, _getFreeLiquidityTokenId(isCallPool), amount); uint256 nextBatch = (block.timestamp / BATCHING_PERIOD) * BATCHING_PERIOD + BATCHING_PERIOD; l.pendingDeposits[account][nextBatch][isCallPool] += amount; PoolStorage.BatchData storage batchData = l.nextDeposits[isCallPool]; batchData.totalPendingDeposits += amount; batchData.eta = nextBatch; } function _processPendingDeposits(PoolStorage.Layout storage l, bool isCall) internal { PoolStorage.BatchData storage batchData = l.nextDeposits[isCall]; if (batchData.eta == 0 || block.timestamp < batchData.eta) return; int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel( l, oldLiquidity64x64, oldLiquidity64x64.add( ABDKMath64x64Token.fromDecimals( batchData.totalPendingDeposits, l.getTokenDecimals(isCall) ) ), isCall ); delete l.nextDeposits[isCall]; } function _getFreeLiquidityTokenId(bool isCall) internal view returns (uint256 freeLiqTokenId) { freeLiqTokenId = isCall ? UNDERLYING_FREE_LIQ_TOKEN_ID : BASE_FREE_LIQ_TOKEN_ID; } function _getReservedLiquidityTokenId(bool isCall) internal view returns (uint256 reservedLiqTokenId) { reservedLiqTokenId = isCall ? UNDERLYING_RESERVED_LIQ_TOKEN_ID : BASE_RESERVED_LIQ_TOKEN_ID; } function _setCLevel( PoolStorage.Layout storage l, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal { int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCallPool); int128 cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, isCallPool ); l.setCLevel(cLevel64x64, isCallPool); emit UpdateCLevel( isCallPool, cLevel64x64, oldLiquidity64x64, newLiquidity64x64 ); } function _updateCLevelAverage( PoolStorage.Layout storage l, uint256 longTokenId, uint256 contractSize, int128 cLevel64x64 ) internal { int128 supply64x64 = ABDKMath64x64Token.fromDecimals( _totalSupply(longTokenId), l.underlyingDecimals ); int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( contractSize, l.underlyingDecimals ); l.avgCLevel64x64[longTokenId] = l .avgCLevel64x64[longTokenId] .mul(supply64x64) .add(cLevel64x64.mul(contractSize64x64)) .div(supply64x64.add(contractSize64x64)); } /** * @notice calculate and store updated market state * @param l storage layout struct * @return newPrice64x64 64x64 fixed point representation of current spot price */ function _update(PoolStorage.Layout storage l) internal returns (int128 newPrice64x64) { if (l.updatedAt == block.timestamp) { return (l.getPriceUpdate(block.timestamp)); } newPrice64x64 = l.fetchPriceUpdate(); if (l.getPriceUpdate(block.timestamp) == 0) { l.setPriceUpdate(block.timestamp, newPrice64x64); } l.updatedAt = block.timestamp; _processPendingDeposits(l, true); _processPendingDeposits(l, false); } /** * @notice transfer ERC20 tokens to message sender * @param token ERC20 token address * @param amount quantity of token to transfer */ function _pushTo( address to, address token, uint256 amount ) internal { if (amount == 0) return; require(IERC20(token).transfer(to, amount), "ERC20 transfer failed"); } /** * @notice transfer ERC20 tokens from message sender * @param l storage layout struct * @param from address from which tokens are pulled from * @param amount quantity of token to transfer * @param isCallPool whether funds correspond to call or put pool * @param creditMessageValue whether to attempt to treat message value as credit */ function _pullFrom( PoolStorage.Layout storage l, address from, uint256 amount, bool isCallPool, bool creditMessageValue ) internal { uint256 credit; if (creditMessageValue) { credit = _creditMessageValue(amount, isCallPool); } if (amount > credit) { credit += _creditReservedLiquidity( from, amount - credit, isCallPool ); } if (amount > credit) { require( IERC20(l.getPoolToken(isCallPool)).transferFrom( from, address(this), amount - credit ), "ERC20 transfer failed" ); } } /** * @notice transfer or reinvest available user funds * @param account owner of funds * @param amount quantity of funds available * @param isCallPool whether funds correspond to call or put pool * @param divest whether to reserve funds or reinvest * @param transferOnDivest whether to transfer divested funds to owner */ function _processAvailableFunds( address account, uint256 amount, bool isCallPool, bool divest, bool transferOnDivest ) internal { if (divest) { if (transferOnDivest) { _pushTo( account, PoolStorage.layout().getPoolToken(isCallPool), amount ); } else { _mint( account, _getReservedLiquidityTokenId(isCallPool), amount ); } } else { _addToDepositQueue(account, amount, isCallPool); } } /** * @notice validate that pool accepts ether deposits and calculate credit amount from message value * @param amount total deposit quantity * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @return credit quantity of credit to apply */ function _creditMessageValue(uint256 amount, bool isCallPool) internal returns (uint256 credit) { if (msg.value > 0) { require( PoolStorage.layout().getPoolToken(isCallPool) == WETH_ADDRESS, "not WETH deposit" ); if (msg.value > amount) { unchecked { (bool success, ) = payable(msg.sender).call{ value: msg.value - amount }(""); require(success, "ETH refund failed"); credit = amount; } } else { credit = msg.value; } IWETH(WETH_ADDRESS).deposit{value: credit}(); } } /** * @notice calculate credit amount from reserved liquidity * @param account address whose reserved liquidity to use as credit * @param amount total deposit quantity * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @return credit quantity of credit to apply */ function _creditReservedLiquidity( address account, uint256 amount, bool isCallPool ) internal returns (uint256 credit) { uint256 reservedLiqTokenId = _getReservedLiquidityTokenId(isCallPool); uint256 balance = _balanceOf(account, reservedLiqTokenId); if (balance > 0) { credit = balance > amount ? amount : balance; _burn(account, reservedLiqTokenId, credit); } } function _mint( address account, uint256 tokenId, uint256 amount ) internal { _mint(account, tokenId, amount, ""); } function _addUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, userTVL + amount, totalTVL ); l.userTVL[user][isCallPool] = userTVL + amount; l.totalTVL[isCallPool] = totalTVL + amount; } function _subUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; uint256 newUserTVL; uint256 newTotalTVL; if (userTVL > amount) { newUserTVL = userTVL - amount; } if (totalTVL > amount) { newTotalTVL = totalTVL - amount; } IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, newUserTVL, totalTVL ); l.userTVL[user][isCallPool] = newUserTVL; l.totalTVL[isCallPool] = newTotalTVL; } /** * @notice ERC1155 hook: track eligible underwriters * @param operator transaction sender * @param from token sender * @param to token receiver * @param ids token ids transferred * @param amounts token quantities transferred * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); PoolStorage.Layout storage l = PoolStorage.layout(); for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; if (amount == 0) continue; if (from == address(0)) { l.tokenIds.add(id); } if (to == address(0) && _totalSupply(id) == 0) { l.tokenIds.remove(id); } // prevent transfer of free and reserved liquidity during waiting period if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID || id == BASE_RESERVED_LIQ_TOKEN_ID ) { if (from != address(0) && to != address(0)) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID; require( l.depositedAt[from][isCallPool] + (1 days) < block.timestamp, "liq lock 1d" ); } } if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID ) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 minimum = l.getMinimumAmount(isCallPool); if (from != address(0)) { uint256 balance = _balanceOf(from, id); if (balance > minimum && balance <= amount + minimum) { require( balance - l.pendingDepositsOf(from, isCallPool) >= amount, "Insuf balance" ); l.removeUnderwriter(from, isCallPool); } if (to != address(0)) { _subUserTVL(l, from, isCallPool, amount); _addUserTVL(l, to, isCallPool, amount); } } if (to != address(0)) { uint256 balance = _balanceOf(to, id); if (balance <= minimum && balance + amount >= minimum) { l.addUnderwriter(to, isCallPool); } } } // Update userTVL on SHORT options transfers (PoolStorage.TokenType tokenType, , ) = PoolStorage.parseTokenId( id ); if ( tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.SHORT_PUT ) { _beforeShortTokenTransfer(l, from, to, id, amount); } } } function _beforeShortTokenTransfer( PoolStorage.Layout storage l, address from, address to, uint256 id, uint256 amount ) private { // total supply has already been updated, so compare to amount rather than 0 if (from == address(0) && _totalSupply(id) == amount) { l.feeReserveRates[id] = FEE_APY_64x64; } if (to == address(0) && _totalSupply(id) == 0) { delete l.feeReserveRates[id]; } if (from != address(0) && to != address(0)) { ( PoolStorage.TokenType tokenType, uint64 maturity, int128 strike64x64 ) = PoolStorage.parseTokenId(id); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL; uint256 collateral = l.contractSizeToBaseTokenAmount( amount, strike64x64, isCall ); uint256 intervalApyFee = _calculateApyFee( l, id, collateral, maturity ); uint256 rebate = _fulfillApyFee( l, from, id, amount, intervalApyFee, isCall ); _reserveApyFee(l, to, id, intervalApyFee); bool divest = !l.getReinvestmentStatus(from, isCall); if (rebate > 0) { _processAvailableFunds(from, rebate, isCall, divest, false); } _subUserTVL( l, from, isCall, divest ? collateral : collateral - rebate ); _addUserTVL(l, to, isCall, collateral); } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol"; import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; library PoolStorage { using ABDKMath64x64 for int128; using PoolStorage for PoolStorage.Layout; enum TokenType { UNDERLYING_FREE_LIQ, BASE_FREE_LIQ, UNDERLYING_RESERVED_LIQ, BASE_RESERVED_LIQ, LONG_CALL, SHORT_CALL, LONG_PUT, SHORT_PUT } struct PoolSettings { address underlying; address base; address underlyingOracle; address baseOracle; } struct QuoteArgsInternal { address feePayer; // address of the fee payer uint64 maturity; // timestamp of option maturity int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price uint256 contractSize; // size of option contract bool isCall; // true for call, false for put } struct QuoteResultInternal { int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee) int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size } struct BatchData { uint256 eta; uint256 totalPendingDeposits; } bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.Pool"); uint256 private constant C_DECAY_BUFFER = 12 hours; uint256 private constant C_DECAY_INTERVAL = 4 hours; struct Layout { // ERC20 token addresses address base; address underlying; // AggregatorV3Interface oracle addresses address baseOracle; address underlyingOracle; // token metadata uint8 underlyingDecimals; uint8 baseDecimals; // minimum amounts uint256 baseMinimum; uint256 underlyingMinimum; // deposit caps uint256 _deprecated_basePoolCap; uint256 _deprecated_underlyingPoolCap; // market state int128 _deprecated_steepness64x64; int128 cLevelBase64x64; int128 cLevelUnderlying64x64; uint256 cLevelBaseUpdatedAt; uint256 cLevelUnderlyingUpdatedAt; uint256 updatedAt; // User -> isCall -> depositedAt mapping(address => mapping(bool => uint256)) depositedAt; mapping(address => mapping(bool => uint256)) divestmentTimestamps; // doubly linked list of free liquidity intervals // isCall -> User -> User mapping(bool => mapping(address => address)) liquidityQueueAscending; mapping(bool => mapping(address => address)) liquidityQueueDescending; // minimum resolution price bucket => price mapping(uint256 => int128) bucketPrices64x64; // sequence id (minimum resolution price bucket / 256) => price update sequence mapping(uint256 => uint256) priceUpdateSequences; // isCall -> batch data mapping(bool => BatchData) nextDeposits; // user -> batch timestamp -> isCall -> pending amount mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits; EnumerableSet.UintSet tokenIds; // user -> isCallPool -> total value locked of user (Used for liquidity mining) mapping(address => mapping(bool => uint256)) userTVL; // isCallPool -> total value locked mapping(bool => uint256) totalTVL; // steepness values int128 steepnessBase64x64; int128 steepnessUnderlying64x64; // User -> isCallPool -> isBuybackEnabled mapping(address => mapping(bool => bool)) isBuybackEnabled; // LongTokenId -> averageC mapping(uint256 => int128) avgCLevel64x64; // APY fee tracking // underwriter -> shortTokenId -> amount mapping(address => mapping(uint256 => uint256)) feesReserved; // shortTokenId -> 64x64 fixed point representation of apy fee mapping(uint256 => int128) feeReserveRates; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } /** * @notice calculate ERC1155 token id for given option parameters * @param tokenType TokenType enum * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @return tokenId token id */ function formatTokenId( TokenType tokenType, uint64 maturity, int128 strike64x64 ) internal pure returns (uint256 tokenId) { tokenId = (uint256(tokenType) << 248) + (uint256(maturity) << 128) + uint256(int256(strike64x64)); } /** * @notice derive option maturity and strike price from ERC1155 token id * @param tokenId token id * @return tokenType TokenType enum * @return maturity timestamp of option maturity * @return strike64x64 option strike price */ function parseTokenId(uint256 tokenId) internal pure returns ( TokenType tokenType, uint64 maturity, int128 strike64x64 ) { assembly { tokenType := shr(248, tokenId) maturity := shr(128, tokenId) strike64x64 := tokenId } } function getTokenType(bool isCall, bool isLong) internal pure returns (TokenType tokenType) { if (isCall) { tokenType = isLong ? TokenType.LONG_CALL : TokenType.SHORT_CALL; } else { tokenType = isLong ? TokenType.LONG_PUT : TokenType.SHORT_PUT; } } function getPoolToken(Layout storage l, bool isCall) internal view returns (address token) { token = isCall ? l.underlying : l.base; } function getTokenDecimals(Layout storage l, bool isCall) internal view returns (uint8 decimals) { decimals = isCall ? l.underlyingDecimals : l.baseDecimals; } function getMinimumAmount(Layout storage l, bool isCall) internal view returns (uint256 minimumAmount) { minimumAmount = isCall ? l.underlyingMinimum : l.baseMinimum; } /** * @notice get the total supply of free liquidity tokens, minus pending deposits * @param l storage layout struct * @param isCall whether query is for call or put pool * @return 64x64 fixed point representation of total free liquidity */ function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall) internal view returns (int128) { uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); return ABDKMath64x64Token.fromDecimals( ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.totalPendingDeposits(isCall), l.getTokenDecimals(isCall) ); } function getReinvestmentStatus( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { uint256 timestamp = l.divestmentTimestamps[account][isCallPool]; return timestamp == 0 || timestamp > block.timestamp; } function addUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (_isInQueue(account, asc, desc)) return; address last = desc[address(0)]; asc[last] = account; desc[account] = last; desc[address(0)] = account; } function removeUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (!_isInQueue(account, asc, desc)) return; address prev = desc[account]; address next = asc[account]; asc[prev] = next; desc[next] = prev; delete asc[account]; delete desc[account]; } function isInQueue( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; return _isInQueue(account, asc, desc); } function _isInQueue( address account, mapping(address => address) storage asc, mapping(address => address) storage desc ) private view returns (bool) { return asc[account] != address(0) || desc[address(0)] == account; } /** * @notice get current C-Level, without accounting for pending adjustments * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getRawCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64; } /** * @notice get current C-Level, accounting for unrealized decay * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getDecayAdjustedCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { // get raw C-Level from storage cLevel64x64 = l.getRawCLevel64x64(isCall); // account for C-Level decay cLevel64x64 = l.applyCLevelDecayAdjustment(cLevel64x64, isCall); } /** * @notice get updated C-Level and pool liquidity level, accounting for decay and pending deposits * @param l storage layout struct * @param isCall whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level * @return liquidity64x64 64x64 fixed point representation of new liquidity amount */ function getRealPoolState(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64, int128 liquidity64x64) { PoolStorage.BatchData storage batchData = l.nextDeposits[isCall]; int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCall); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); if ( batchData.totalPendingDeposits > 0 && batchData.eta != 0 && block.timestamp >= batchData.eta ) { liquidity64x64 = ABDKMath64x64Token .fromDecimals( batchData.totalPendingDeposits, l.getTokenDecimals(isCall) ) .add(oldLiquidity64x64); cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, liquidity64x64, isCall ); } else { cLevel64x64 = oldCLevel64x64; liquidity64x64 = oldLiquidity64x64; } } /** * @notice calculate updated C-Level, accounting for unrealized decay * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for decay * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after accounting for decay */ function applyCLevelDecayAdjustment( Layout storage l, int128 oldCLevel64x64, bool isCall ) internal view returns (int128 cLevel64x64) { uint256 timeElapsed = block.timestamp - (isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt); // do not apply C decay if less than 24 hours have elapsed if (timeElapsed > C_DECAY_BUFFER) { timeElapsed -= C_DECAY_BUFFER; } else { return oldCLevel64x64; } int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu( timeElapsed, C_DECAY_INTERVAL ); uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); uint256 tvl = l.totalTVL[isCall]; int128 utilization = ABDKMath64x64.divu( tvl - (ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.totalPendingDeposits(isCall)), tvl ); return OptionMath.calculateCLevelDecay( OptionMath.CalculateCLevelDecayArgs( timeIntervalsElapsed64x64, oldCLevel64x64, utilization, 0xb333333333333333, // 0.7 0xe666666666666666, // 0.9 0x10000000000000000, // 1.0 0x10000000000000000, // 1.0 0xe666666666666666, // 0.9 0x56fc2a2c515da32ea // 2e ) ); } /** * @notice calculate updated C-Level, accounting for change in liquidity * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for liquidity change * @param oldLiquidity64x64 64x64 fixed point representation of previous liquidity * @param newLiquidity64x64 64x64 fixed point representation of current liquidity * @param isCallPool whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function applyCLevelLiquidityChangeAdjustment( Layout storage l, int128 oldCLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal view returns (int128 cLevel64x64) { int128 steepness64x64 = isCallPool ? l.steepnessUnderlying64x64 : l.steepnessBase64x64; // fallback to deprecated storage value if side-specific value is not set if (steepness64x64 == 0) steepness64x64 = l._deprecated_steepness64x64; cLevel64x64 = OptionMath.calculateCLevel( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, steepness64x64 ); if (cLevel64x64 < 0xb333333333333333) { cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7 } } /** * @notice set C-Level to arbitrary pre-calculated value * @param cLevel64x64 new C-Level of pool * @param isCallPool whether to update C-Level for call or put pool */ function setCLevel( Layout storage l, int128 cLevel64x64, bool isCallPool ) internal { if (isCallPool) { l.cLevelUnderlying64x64 = cLevel64x64; l.cLevelUnderlyingUpdatedAt = block.timestamp; } else { l.cLevelBase64x64 = cLevel64x64; l.cLevelBaseUpdatedAt = block.timestamp; } } function setOracles( Layout storage l, address baseOracle, address underlyingOracle ) internal { require( AggregatorV3Interface(baseOracle).decimals() == AggregatorV3Interface(underlyingOracle).decimals(), "Pool: oracle decimals must match" ); l.baseOracle = baseOracle; l.underlyingOracle = underlyingOracle; } function fetchPriceUpdate(Layout storage l) internal view returns (int128 price64x64) { int256 priceUnderlying = AggregatorInterface(l.underlyingOracle) .latestAnswer(); int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer(); return ABDKMath64x64.divi(priceUnderlying, priceBase); } /** * @notice set price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to update * @param price64x64 64x64 fixed point representation of price */ function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64 ) internal { uint256 bucket = timestamp / (1 hours); l.bucketPrices64x64[bucket] = price64x64; l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255)); } /** * @notice get price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdate(Layout storage l, uint256 timestamp) internal view returns (int128) { return l.bucketPrices64x64[timestamp / (1 hours)]; } /** * @notice get first price update available following given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdateAfter(Layout storage l, uint256 timestamp) internal view returns (int128) { // price updates are grouped into hourly buckets uint256 bucket = timestamp / (1 hours); // divide by 256 to get the index of the relevant price update sequence uint256 sequenceId = bucket >> 8; // get position within sequence relevant to current price update uint256 offset = bucket & 255; // shift to skip buckets from earlier in sequence uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >> offset; // iterate through future sequences until a price update is found // sequence corresponding to current timestamp used as upper bound uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours); while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) { sequence = l.priceUpdateSequences[++sequenceId]; } // if no price update is found (sequence == 0) function will return 0 // this should never occur, as each relevant external function triggers a price update // the most significant bit of the sequence corresponds to the offset of the relevant bucket uint256 msb; for (uint256 i = 128; i > 0; i >>= 1) { if (sequence >> i > 0) { msb += i; sequence >>= i; } } return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1]; } function totalPendingDeposits(Layout storage l, bool isCallPool) internal view returns (uint256) { return l.nextDeposits[isCallPool].totalPendingDeposits; } function pendingDepositsOf( Layout storage l, address account, bool isCallPool ) internal view returns (uint256) { return l.pendingDeposits[account][l.nextDeposits[isCallPool].eta][ isCallPool ]; } function contractSizeToBaseTokenAmount( Layout storage l, uint256 contractSize, int128 price64x64, bool isCallPool ) internal view returns (uint256 tokenAmount) { if (isCallPool) { tokenAmount = contractSize; } else { uint256 value = price64x64.mulu(contractSize); int128 value64x64 = ABDKMath64x64Token.fromDecimals( value, l.underlyingDecimals ); tokenAmount = ABDKMath64x64Token.toDecimals( value64x64, l.baseDecimals ); } } function setBuybackEnabled( Layout storage l, bool state, bool isCallPool ) internal { l.isBuybackEnabled[msg.sender][isCallPool] = state; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC1155Metadata interface */ interface IERC1155Metadata { /** * @notice get generated URI for given token * @return token URI */ function uri(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; library ERC1155EnumerableStorage { struct Layout { mapping(uint256 => uint256) totalSupply; mapping(uint256 => EnumerableSet.AddressSet) accountsByToken; mapping(address => EnumerableSet.UintSet) tokensByAccount; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Enumerable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library ABDKMath64x64Token { using ABDKMath64x64 for int128; /** * @notice convert 64x64 fixed point representation of token amount to decimal * @param value64x64 64x64 fixed point representation of token amount * @param decimals token display decimals * @return value decimal representation of token amount */ function toDecimals(int128 value64x64, uint8 decimals) internal pure returns (uint256 value) { value = value64x64.mulu(10**decimals); } /** * @notice convert decimal representation of token amount to 64x64 fixed point * @param value decimal representation of token amount * @param decimals token display decimals * @return value64x64 64x64 fixed point representation of token amount */ function fromDecimals(uint256 value, uint8 decimals) internal pure returns (int128 value64x64) { value64x64 = ABDKMath64x64.divu(value, 10**decimals); } /** * @notice convert 64x64 fixed point representation of token amount to wei (18 decimals) * @param value64x64 64x64 fixed point representation of token amount * @return value wei representation of token amount */ function toWei(int128 value64x64) internal pure returns (uint256 value) { value = toDecimals(value64x64, 18); } /** * @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point * @param value wei representation of token amount * @return value64x64 64x64 fixed point representation of token amount */ function fromWei(uint256 value) internal pure returns (int128 value64x64) { value64x64 = fromDecimals(value, 18); } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library OptionMath { using ABDKMath64x64 for int128; struct QuoteArgs { int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years) int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase int128 oldPoolState; // 64x64 fixed point representation of current state of the pool int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options bool isCall; // whether to price "call" or "put" option } struct CalculateCLevelDecayArgs { int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate int128 utilizationLowerBound64x64; int128 utilizationUpperBound64x64; int128 cLevelLowerBound64x64; int128 cLevelUpperBound64x64; int128 cConvergenceULowerBound64x64; int128 cConvergenceUUpperBound64x64; } // 64x64 fixed point integer constants int128 internal constant ONE_64x64 = 0x10000000000000000; int128 internal constant THREE_64x64 = 0x30000000000000000; // 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989 int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989 int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989 /** * @notice recalculate C-Level based on change in liquidity * @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update * @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update * @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update * @param steepness64x64 64x64 fixed point representation of steepness coefficient * @return 64x64 fixed point representation of new C-Level */ function calculateCLevel( int128 initialCLevel64x64, int128 oldPoolState64x64, int128 newPoolState64x64, int128 steepness64x64 ) external pure returns (int128) { return newPoolState64x64 .sub(oldPoolState64x64) .div( oldPoolState64x64 > newPoolState64x64 ? oldPoolState64x64 : newPoolState64x64 ) .mul(steepness64x64) .neg() .exp() .mul(initialCLevel64x64); } /** * @notice calculate the price of an option using the Premia Finance model * @param args arguments of quotePrice * @return premiaPrice64x64 64x64 fixed point representation of Premia option price * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase */ function quotePrice(QuoteArgs memory args) external pure returns ( int128 premiaPrice64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) { int128 deltaPoolState64x64 = args .newPoolState .sub(args.oldPoolState) .div(args.oldPoolState) .mul(args.steepness64x64); int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp(); int128 blackScholesPrice64x64 = _blackScholesPrice( args.varianceAnnualized64x64, args.strike64x64, args.spot64x64, args.timeToMaturity64x64, args.isCall ); cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64); slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div( deltaPoolState64x64 ); premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul( slippageCoefficient64x64 ); int128 intrinsicValue64x64; if (args.isCall && args.strike64x64 < args.spot64x64) { intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64); } else if (!args.isCall && args.strike64x64 > args.spot64x64) { intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64); } int128 collateralValue64x64 = args.isCall ? args.spot64x64 : args.strike64x64; int128 minPrice64x64 = intrinsicValue64x64.add( collateralValue64x64.mul(args.minAPY64x64).mul( args.timeToMaturity64x64 ) ); if (minPrice64x64 > premiaPrice64x64) { premiaPrice64x64 = minPrice64x64; } } /** * @notice calculate the decay of C-Level based on heat diffusion function * @param args structured CalculateCLevelDecayArgs * @return cLevelDecayed64x64 C-Level after accounting for decay */ function calculateCLevelDecay(CalculateCLevelDecayArgs memory args) external pure returns (int128 cLevelDecayed64x64) { int128 convFHighU64x64 = (args.utilization64x64 >= args.utilizationUpperBound64x64 && args.oldCLevel64x64 <= args.cLevelLowerBound64x64) ? ONE_64x64 : int128(0); int128 convFLowU64x64 = (args.utilization64x64 <= args.utilizationLowerBound64x64 && args.oldCLevel64x64 >= args.cLevelUpperBound64x64) ? ONE_64x64 : int128(0); cLevelDecayed64x64 = args .oldCLevel64x64 .sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64)) .sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)) .mul( convFLowU64x64 .mul(ONE_64x64.sub(args.utilization64x64)) .add(convFHighU64x64.mul(args.utilization64x64)) .mul(args.timeIntervalsElapsed64x64) .neg() .exp() ) .add( args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add( args.cConvergenceUUpperBound64x64.mul(convFHighU64x64) ) ); } /** * @notice calculate the exponential decay coefficient for a given interval * @param oldTimestamp timestamp of previous update * @param newTimestamp current timestamp * @return 64x64 fixed point representation of exponential decay coefficient */ function _decay(uint256 oldTimestamp, uint256 newTimestamp) internal pure returns (int128) { return ONE_64x64.sub( (-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp() ); } /** * @notice calculate Choudhury’s approximation of the Black-Scholes CDF * @param input64x64 64x64 fixed point representation of random variable * @return 64x64 fixed point representation of the approximated CDF of x */ function _N(int128 input64x64) internal pure returns (int128) { // squaring via mul is cheaper than via pow int128 inputSquared64x64 = input64x64.mul(input64x64); int128 value64x64 = (-inputSquared64x64 >> 1).exp().div( CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add( CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt()) ) ); return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64; } /** * @notice calculate the price of an option using the Black-Scholes model * @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance * @param strike64x64 64x64 fixed point representation of strike price * @param spot64x64 64x64 fixed point representation of spot price * @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years) * @param isCall whether to price "call" or "put" option * @return 64x64 fixed point representation of Black-Scholes option price */ function _blackScholesPrice( int128 varianceAnnualized64x64, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) internal pure returns (int128) { int128 cumulativeVariance64x64 = timeToMaturity64x64.mul( varianceAnnualized64x64 ); int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt(); int128 d1_64x64 = spot64x64 .div(strike64x64) .ln() .add(cumulativeVariance64x64 >> 1) .div(cumulativeVarianceSqrt64x64); int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64); if (isCall) { return spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64))); } else { return -spot64x64.mul(_N(-d1_64x64)).sub( strike64x64.mul(_N(-d2_64x64)) ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Contract ownership standard interface * @dev see https://eips.ethereum.org/EIPS/eip-173 */ interface IERC173 { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @notice get the ERC173 contract owner * @return conract owner */ function owner() external view returns (address); /** * @notice transfer contract ownership to new account * @param account address of new owner */ function transferOwnership(address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library OwnableStorage { struct Layout { address owner; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.Ownable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function setOwner(Layout storage l, address owner) internal { l.owner = owner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20Internal } from './IERC20Internal.sol'; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 is IERC20Internal { /** * @notice query the total minted token supply * @return token supply */ function totalSupply() external view returns (uint256); /** * @notice query the token balance of given account * @param account address to query * @return token balance */ function balanceOf(address account) external view returns (uint256); /** * @notice query the allowance granted from given holder to given spender * @param holder approver of allowance * @param spender recipient of allowance * @return token allowance */ function allowance(address holder, address spender) external view returns (uint256); /** * @notice grant approval to spender to spend tokens * @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729) * @param spender recipient of allowance * @param amount quantity of tokens approved for spending * @return success status (always true; otherwise function should revert) */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient on behalf of given holder * @param holder holder of tokens prior to transfer * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transferFrom( address holder, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155Base, ERC1155BaseInternal } from '../base/ERC1155Base.sol'; import { IERC1155Enumerable } from './IERC1155Enumerable.sol'; import { ERC1155EnumerableInternal, ERC1155EnumerableStorage } from './ERC1155EnumerableInternal.sol'; /** * @title ERC1155 implementation including enumerable and aggregate functions */ abstract contract ERC1155Enumerable is IERC1155Enumerable, ERC1155Base, ERC1155EnumerableInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @inheritdoc IERC1155Enumerable */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply(id); } /** * @inheritdoc IERC1155Enumerable */ function totalHolders(uint256 id) public view virtual returns (uint256) { return _totalHolders(id); } /** * @inheritdoc IERC1155Enumerable */ function accountsByToken(uint256 id) public view virtual returns (address[] memory) { return _accountsByToken(id); } /** * @inheritdoc IERC1155Enumerable */ function tokensByAccount(address account) public view virtual returns (uint256[] memory) { return _tokensByAccount(account); } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155EnumerableInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155BaseInternal, ERC1155EnumerableInternal) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from '../token/ERC20/IERC20.sol'; import { IERC20Metadata } from '../token/ERC20/metadata/IERC20Metadata.sol'; /** * @title WETH (Wrapped ETH) interface */ interface IWETH is IERC20, IERC20Metadata { /** * @notice convert ETH to WETH */ function deposit() external payable; /** * @notice convert WETH to ETH * @dev if caller is a contract, it should have a fallback or receive function * @param amount quantity of WETH to convert, denominated in wei */ function withdraw(uint256 amount) external; } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {FeeDiscountStorage} from "./FeeDiscountStorage.sol"; interface IFeeDiscount { event Staked( address indexed user, uint256 amount, uint256 stakePeriod, uint256 lockedUntil ); event Unstaked(address indexed user, uint256 amount); struct StakeLevel { uint256 amount; // Amount to stake uint256 discount; // Discount when amount is reached } /** * @notice Stake using IERC2612 permit * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) * @param deadline Deadline after which permit will fail * @param v V * @param r R * @param s S */ function stakeWithPermit( uint256 amount, uint256 period, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Lockup xPremia for protocol fee discounts * Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) */ function stake(uint256 amount, uint256 period) external; /** * @notice Unstake xPremia (If lockup period has ended) * @param amount The amount of xPremia to unstake */ function unstake(uint256 amount) external; ////////// // View // ////////// /** * Calculate the stake amount of a user, after applying the bonus from the lockup period chosen * @param user The user from which to query the stake amount * @return The user stake amount after applying the bonus */ function getStakeAmountWithBonus(address user) external view returns (uint256); /** * @notice Calculate the % of fee discount for user, based on his stake * @param user The _user for which the discount is for * @return Percentage of protocol fee discount (in basis point) * Ex : 1000 = 10% fee discount */ function getDiscount(address user) external view returns (uint256); /** * @notice Get stake levels * @return Stake levels * Ex : 2500 = -25% */ function getStakeLevels() external returns (StakeLevel[] memory); /** * @notice Get stake period multiplier * @param period The duration (in seconds) for which tokens are locked * @return The multiplier for this staking period * Ex : 20000 = x2 */ function getStakePeriodMultiplier(uint256 period) external returns (uint256); /** * @notice Get staking infos of a user * @param user The user address for which to get staking infos * @return The staking infos of the user */ function getUserInfo(address user) external view returns (FeeDiscountStorage.UserInfo memory); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; interface IPoolEvents { event Purchase( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 baseCost, uint256 feeCost, int128 spot64x64 ); event Sell( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 baseCost, uint256 feeCost, int128 spot64x64 ); event Exercise( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 exerciseValue, uint256 fee ); event Underwrite( address indexed underwriter, address indexed longReceiver, uint256 shortTokenId, uint256 intervalContractSize, uint256 intervalPremium, bool isManualUnderwrite ); event AssignExercise( address indexed underwriter, uint256 shortTokenId, uint256 freedAmount, uint256 intervalContractSize, uint256 fee ); event AssignSale( address indexed underwriter, uint256 shortTokenId, uint256 freedAmount, uint256 intervalContractSize ); event Deposit(address indexed user, bool isCallPool, uint256 amount); event Withdrawal( address indexed user, bool isCallPool, uint256 depositedAt, uint256 amount ); event FeeWithdrawal(bool indexed isCallPool, uint256 amount); event APYFeeReserved( address underwriter, uint256 shortTokenId, uint256 amount ); event APYFeePaid(address underwriter, uint256 shortTokenId, uint256 amount); event Annihilate(uint256 shortTokenId, uint256 amount); event UpdateCLevel( bool indexed isCall, int128 cLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64 ); event UpdateSteepness(int128 steepness64x64, bool isCallPool); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {PremiaMiningStorage} from "./PremiaMiningStorage.sol"; interface IPremiaMining { function addPremiaRewards(uint256 _amount) external; function premiaRewardsAvailable() external view returns (uint256); function getTotalAllocationPoints() external view returns (uint256); function getPoolInfo(address pool, bool isCallPool) external view returns (PremiaMiningStorage.PoolInfo memory); function getPremiaPerYear() external view returns (uint256); function addPool(address _pool, uint256 _allocPoints) external; function setPoolAllocPoints( address[] memory _pools, uint256[] memory _allocPoints ) external; function pendingPremia( address _pool, bool _isCallPool, address _user ) external view returns (uint256); function updatePool( address _pool, bool _isCallPool, uint256 _totalTVL ) external; function allocatePending( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; function claim( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {VolatilitySurfaceOracleStorage} from "./VolatilitySurfaceOracleStorage.sol"; interface IVolatilitySurfaceOracle { /** * @notice Pack IV model parameters into a single bytes32 * @dev This function is used to pack the parameters into a single variable, which is then used as input in `update` * @param params Parameters of IV model to pack * @return result The packed parameters of IV model */ function formatParams(int256[5] memory params) external pure returns (bytes32 result); /** * @notice Unpack IV model parameters from a bytes32 * @param input Packed IV model parameters to unpack * @return params The unpacked parameters of the IV model */ function parseParams(bytes32 input) external pure returns (int256[] memory params); /** * @notice Get the list of whitelisted relayers * @return The list of whitelisted relayers */ function getWhitelistedRelayers() external view returns (address[] memory); /** * @notice Get the IV model parameters of a token pair * @param base The base token of the pair * @param underlying The underlying token of the pair * @return The IV model parameters */ function getParams(address base, address underlying) external view returns (VolatilitySurfaceOracleStorage.Update memory); /** * @notice Get unpacked IV model parameters * @param base The base token of the pair * @param underlying The underlying token of the pair * @return The unpacked IV model parameters */ function getParamsUnpacked(address base, address underlying) external view returns (int256[] memory); /** * @notice Get time to maturity in years, as a 64x64 fixed point representation * @param maturity Maturity timestamp * @return Time to maturity (in years), as a 64x64 fixed point representation */ function getTimeToMaturity64x64(uint64 maturity) external view returns (int128); /** * @notice calculate the annualized volatility for given set of parameters * @param base The base token of the pair * @param underlying The underlying token of the pair * @param spot64x64 64x64 fixed point representation of spot price * @param strike64x64 64x64 fixed point representation of strike price * @param timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years) * @return 64x64 fixed point representation of annualized implied volatility, where 1 is defined as 100% */ function getAnnualizedVolatility64x64( address base, address underlying, int128 spot64x64, int128 strike64x64, int128 timeToMaturity64x64 ) external view returns (int128); /** * @notice calculate the price of an option using the Black-Scholes model * @param base The base token of the pair * @param underlying The underlying token of the pair * @param strike64x64 Strike, as a64x64 fixed point representation * @param spot64x64 Spot price, as a 64x64 fixed point representation * @param timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years) * @param isCall Whether it is for call or put * @return 64x64 fixed point representation of the Black Scholes price */ function getBlackScholesPrice64x64( address base, address underlying, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (int128); /** * @notice Get Black Scholes price as an uint256 with 18 decimals * @param base The base token of the pair * @param underlying The underlying token of the pair * @param strike64x64 Strike, as a64x64 fixed point representation * @param spot64x64 Spot price, as a 64x64 fixed point representation * @param timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years) * @param isCall Whether it is for call or put * @return Black scholes price, as an uint256 with 18 decimals */ function getBlackScholesPrice( address base, address underlying, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (uint256); /** * @notice Add relayers to the whitelist so that they can add oracle surfaces * @param accounts The addresses to add to the whitelist */ function addWhitelistedRelayers(address[] memory accounts) external; /** * @notice Remove relayers from the whitelist so that they cannot add oracle surfaces * @param accounts The addresses to remove from the whitelist */ function removeWhitelistedRelayers(address[] memory accounts) external; /** * @notice Update a list of IV model parameters * @param base List of base tokens * @param underlying List of underlying tokens * @param parameters List of IV model parameters */ function updateParams( address[] memory base, address[] memory underlying, bytes32[] memory parameters ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Partial ERC20 interface needed by internal functions */ interface IERC20Internal { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155 } from '../IERC1155.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from './ERC1155BaseInternal.sol'; /** * @title Base ERC1155 contract * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155Base is IERC1155, ERC1155BaseInternal { /** * @inheritdoc IERC1155 */ function balanceOf(address account, uint256 id) public view virtual returns (uint256) { return _balanceOf(account, id); } /** * @inheritdoc IERC1155 */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual returns (uint256[] memory) { require( accounts.length == ids.length, 'ERC1155: accounts and ids length mismatch' ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; uint256[] memory batchBalances = new uint256[](accounts.length); unchecked { for (uint256 i; i < accounts.length; i++) { require( accounts[i] != address(0), 'ERC1155: batch balance query for the zero address' ); batchBalances[i] = balances[ids[i]][accounts[i]]; } } return batchBalances; } /** * @inheritdoc IERC1155 */ function isApprovedForAll(address account, address operator) public view virtual returns (bool) { return ERC1155BaseStorage.layout().operatorApprovals[account][operator]; } /** * @inheritdoc IERC1155 */ function setApprovalForAll(address operator, bool status) public virtual { require( msg.sender != operator, 'ERC1155: setting approval status for self' ); ERC1155BaseStorage.layout().operatorApprovals[msg.sender][ operator ] = status; emit ApprovalForAll(msg.sender, operator, status); } /** * @inheritdoc IERC1155 */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransfer(msg.sender, from, to, id, amount, data); } /** * @inheritdoc IERC1155 */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransferBatch(msg.sender, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC1155 enumerable and aggregate function interface */ interface IERC1155Enumerable { /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function totalSupply(uint256 id) external view returns (uint256); /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function totalHolders(uint256 id) external view returns (uint256); /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function accountsByToken(uint256 id) external view returns (address[] memory); /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function tokensByAccount(address account) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from '../base/ERC1155BaseInternal.sol'; import { ERC1155EnumerableStorage } from './ERC1155EnumerableStorage.sol'; /** * @title ERC1155Enumerable internal functions */ abstract contract ERC1155EnumerableInternal is ERC1155BaseInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function _totalSupply(uint256 id) internal view virtual returns (uint256) { return ERC1155EnumerableStorage.layout().totalSupply[id]; } /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function _totalHolders(uint256 id) internal view virtual returns (uint256) { return ERC1155EnumerableStorage.layout().accountsByToken[id].length(); } /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function _accountsByToken(uint256 id) internal view virtual returns (address[] memory) { EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage .layout() .accountsByToken[id]; address[] memory addresses = new address[](accounts.length()); unchecked { for (uint256 i; i < accounts.length(); i++) { addresses[i] = accounts.at(i); } } return addresses; } /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function _tokensByAccount(address account) internal view virtual returns (uint256[] memory) { EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage .layout() .tokensByAccount[account]; uint256[] memory ids = new uint256[](tokens.length()); unchecked { for (uint256 i; i < tokens.length(); i++) { ids[i] = tokens.at(i); } } return ids; } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155BaseInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from != to) { ERC1155EnumerableStorage.Layout storage l = ERC1155EnumerableStorage .layout(); mapping(uint256 => EnumerableSet.AddressSet) storage tokenAccounts = l.accountsByToken; EnumerableSet.UintSet storage fromTokens = l.tokensByAccount[from]; EnumerableSet.UintSet storage toTokens = l.tokensByAccount[to]; for (uint256 i; i < ids.length; ) { uint256 amount = amounts[i]; if (amount > 0) { uint256 id = ids[i]; if (from == address(0)) { l.totalSupply[id] += amount; } else if (_balanceOf(from, id) == amount) { tokenAccounts[id].remove(from); fromTokens.remove(id); } if (to == address(0)) { l.totalSupply[id] -= amount; } else if (_balanceOf(to, id) == 0) { tokenAccounts[id].add(to); toTokens.add(id); } } unchecked { i++; } } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155Internal } from './IERC1155Internal.sol'; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice ERC1155 interface * @dev see https://github.com/ethereum/EIPs/issues/1155 */ interface IERC1155 is IERC1155Internal, IERC165 { /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @notice query the balances of given tokens held by given addresses * @param accounts addresss to query * @param ids tokens to query * @return token balances */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @notice query approval status of given operator with respect to given address * @param account address to query for approval granted * @param operator address to query for approval received * @return whether operator is approved to spend tokens held by account */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @notice grant approval to or revoke approval from given operator to spend held tokens * @param operator address whose approval status to update * @param status whether operator should be considered approved */ function setApprovalForAll(address operator, bool status) external; /** * @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param ids list of token IDs * @param amounts list of quantities of tokens to transfer * @param data data payload */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @title ERC1155 transfer receiver interface */ interface IERC1155Receiver is IERC165 { /** * @notice validate receipt of ERC1155 transfer * @param operator executor of transfer * @param from sender of tokens * @param id token ID received * @param value quantity of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @notice validate receipt of ERC1155 batch transfer * @param operator executor of transfer * @param from sender of tokens * @param ids token IDs received * @param values quantities of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { AddressUtils } from '../../../utils/AddressUtils.sol'; import { IERC1155Internal } from '../IERC1155Internal.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseStorage } from './ERC1155BaseStorage.sol'; /** * @title Base ERC1155 internal functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155BaseInternal is IERC1155Internal { using AddressUtils for address; /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function _balanceOf(address account, uint256 id) internal view virtual returns (uint256) { require( account != address(0), 'ERC1155: balance query for the zero address' ); return ERC1155BaseStorage.layout().balances[id][account]; } /** * @notice mint given quantity of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); _beforeTokenTransfer( msg.sender, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data ); ERC1155BaseStorage.layout().balances[id][account] += amount; emit TransferSingle(msg.sender, address(0), account, id, amount); } /** * @notice mint given quantity of tokens for given address * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _safeMint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { _mint(account, id, amount, data); _doSafeTransferAcceptanceCheck( msg.sender, address(0), account, id, amount, data ); } /** * @notice mint batch of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _mintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer( msg.sender, address(0), account, ids, amounts, data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; ) { balances[ids[i]][account] += amounts[i]; unchecked { i++; } } emit TransferBatch(msg.sender, address(0), account, ids, amounts); } /** * @notice mint batch of tokens for given address * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _safeMintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _mintBatch(account, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( msg.sender, address(0), account, ids, amounts, data ); } /** * @notice burn given quantity of tokens held by given address * @param account holder of tokens to burn * @param id token ID * @param amount quantity of tokens to burn */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); _beforeTokenTransfer( msg.sender, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), '' ); mapping(address => uint256) storage balances = ERC1155BaseStorage .layout() .balances[id]; unchecked { require( balances[account] >= amount, 'ERC1155: burn amount exceeds balances' ); balances[account] -= amount; } emit TransferSingle(msg.sender, account, address(0), id, amount); } /** * @notice burn given batch of tokens held by given address * @param account holder of tokens to burn * @param ids token IDs * @param amounts quantities of tokens to burn */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, ''); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; require( balances[id][account] >= amounts[i], 'ERC1155: burn amount exceeds balance' ); balances[id][account] -= amounts[i]; } } emit TransferBatch(msg.sender, account, address(0), ids, amounts); } /** * @notice transfer tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _transfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); _beforeTokenTransfer( operator, sender, recipient, _asSingletonArray(id), _asSingletonArray(amount), data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { uint256 senderBalance = balances[id][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[id][sender] = senderBalance - amount; } balances[id][recipient] += amount; emit TransferSingle(operator, sender, recipient, id, amount); } /** * @notice transfer tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _safeTransfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { _transfer(operator, sender, recipient, id, amount, data); _doSafeTransferAcceptanceCheck( operator, sender, recipient, id, amount, data ); } /** * @notice transfer batch of tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _transferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(operator, sender, recipient, ids, amounts, data); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; ) { uint256 token = ids[i]; uint256 amount = amounts[i]; unchecked { uint256 senderBalance = balances[token][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[token][sender] = senderBalance - amount; i++; } // balance increase cannot be unchecked because ERC1155Base neither tracks nor validates a totalSupply balances[token][recipient] += amount; } emit TransferBatch(operator, sender, recipient, ids, amounts); } /** * @notice transfer batch of tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _safeTransferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _transferBatch(operator, sender, recipient, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( operator, sender, recipient, ids, amounts, data ); } /** * @notice wrap given element in array of length 1 * @param element element to wrap * @return singleton array */ function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155Received.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155BatchReceived.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice ERC1155 hook, called before all transfers including mint and burn * @dev function should be overridden and new implementation must call super * @dev called for both single and batch transfers * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice Partial ERC1155 interface needed by internal functions */ interface IERC1155Internal { event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll( address indexed account, address indexed operator, bool approved ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC165 interface registration interface * @dev see https://eips.ethereum.org/EIPS/eip-165 */ interface IERC165 { /** * @notice query whether contract has registered support for given interface * @param interfaceId interface id * @return bool whether interface is supported */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { UintUtils } from './UintUtils.sol'; library AddressUtils { using UintUtils for uint256; function toString(address account) internal pure returns (string memory) { return uint256(uint160(account)).toHexString(20); } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable account, uint256 amount) internal { (bool success, ) = account.call{ value: amount }(''); require(success, 'AddressUtils: failed to send value'); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'AddressUtils: failed low-level call'); } function functionCall( address target, bytes memory data, string memory error ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, error); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'AddressUtils: failed low-level call with value' ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) internal returns (bytes memory) { require( address(this).balance >= value, 'AddressUtils: insufficient balance for call' ); return _functionCallWithValue(target, data, value, error); } function _functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) private returns (bytes memory) { require( isContract(target), 'AddressUtils: function call to non-contract' ); (bool success, bytes memory returnData) = target.call{ value: value }( data ); if (success) { return returnData; } else if (returnData.length > 0) { assembly { let returnData_size := mload(returnData) revert(add(32, returnData), returnData_size) } } else { revert(error); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC1155BaseStorage { struct Layout { mapping(uint256 => mapping(address => uint256)) balances; mapping(address => mapping(address => bool)) operatorApprovals; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Base'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title utility functions for uint256 operations * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ library UintUtils { bytes16 private constant HEX_SYMBOLS = '0123456789abcdef'; function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 length = 0; for (uint256 temp = value; temp != 0; temp >>= 8) { unchecked { length++; } } return toHexString(value, 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'; unchecked { for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_SYMBOLS[value & 0xf]; value >>= 4; } } require(value == 0, 'UintUtils: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC20 metadata interface */ interface IERC20Metadata { /** * @notice return token name * @return token name */ function name() external view returns (string memory); /** * @notice return token symbol * @return token symbol */ function symbol() external view returns (string memory); /** * @notice return token decimals, generally used only for display purposes * @return token decimals */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library FeeDiscountStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.staking.PremiaFeeDiscount"); struct UserInfo { uint256 balance; // Balance staked by user uint64 stakePeriod; // Stake period selected by user uint64 lockedUntil; // Timestamp at which the lock ends } struct Layout { // User data with xPREMIA balance staked and date at which lock ends mapping(address => UserInfo) userInfo; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library PremiaMiningStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.PremiaMining"); // Info of each pool. struct PoolInfo { uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block. uint256 lastRewardTimestamp; // Last timestamp that PREMIA distribution occurs uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below. } // Info of each user. struct UserInfo { uint256 reward; // Total allocated unclaimed reward uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PREMIA // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPremiaPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } struct Layout { // Total PREMIA left to distribute uint256 premiaAvailable; // Amount of premia distributed per year uint256 premiaPerYear; // pool -> isCallPool -> PoolInfo mapping(address => mapping(bool => PoolInfo)) poolInfo; // pool -> isCallPool -> user -> UserInfo mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 totalAllocPoint; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; library VolatilitySurfaceOracleStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.VolatilitySurfaceOracle"); uint256 internal constant PARAM_BITS = 51; uint256 internal constant PARAM_BITS_MINUS_ONE = 50; uint256 internal constant PARAM_AMOUNT = 5; // START_BIT = PARAM_BITS * (PARAM_AMOUNT - 1) uint256 internal constant START_BIT = 204; struct Update { uint256 updatedAt; bytes32 params; } struct Layout { // Base token -> Underlying token -> Update mapping(address => mapping(address => Update)) parameters; // Relayer addresses which can be trusted to provide accurate option trades EnumerableSet.AddressSet whitelistedRelayers; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function getParams( Layout storage l, address base, address underlying ) internal view returns (bytes32) { return l.parameters[base][underlying].params; } function parseParams(bytes32 input) internal pure returns (int256[] memory params) { params = new int256[](PARAM_AMOUNT); // Value to add to negative numbers to cast them to int256 int256 toAdd = (int256(-1) >> PARAM_BITS) << PARAM_BITS; assembly { let i := 0 // Value equal to -1 let mid := shl(PARAM_BITS_MINUS_ONE, 1) for { } lt(i, PARAM_AMOUNT) { } { let offset := sub(START_BIT, mul(PARAM_BITS, i)) let param := shr( offset, sub( input, shl( add(offset, PARAM_BITS), shr(add(offset, PARAM_BITS), input) ) ) ) // Check if value is a negative number and needs casting if or(eq(param, mid), gt(param, mid)) { param := add(param, toAdd) } // Store result in the params array mstore(add(params, add(0x20, mul(0x20, i))), param) i := add(i, 1) } } } function formatParams(int256[5] memory params) internal pure returns (bytes32 result) { int256 max = int256(1 << PARAM_BITS_MINUS_ONE); unchecked { for (uint256 i = 0; i < PARAM_AMOUNT; i++) { require(params[i] < max && params[i] > -max, "Out of bounds"); } } assembly { let i := 0 for { } lt(i, PARAM_AMOUNT) { } { let offset := sub(START_BIT, mul(PARAM_BITS, i)) let param := mload(add(params, mul(0x20, i))) result := add( result, shl( offset, sub(param, shl(PARAM_BITS, shr(PARAM_BITS, param))) ) ) i := add(i, 1) } } } }
@inheritdoc IPoolView/
function getMinimumAmounts() external view returns (uint256 minCallTokenAmount, uint256 minPutTokenAmount) { PoolStorage.Layout storage l = PoolStorage.layout(); return (l.getMinimumAmount(true), l.getMinimumAmount(false)); }
14,894,330
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol
Reads the bytes25 at `cdPtr` in calldata.
function readBytes25( CalldataPointer cdPtr ) internal pure returns (bytes25 value) { assembly { value := calldataload(cdPtr) } }
4,300,196
./full_match/4/0xcd215a2f9eBE25Bc3ff21662e88d3Bb3D462e40c/sources/contracts/BrilliantNewMagik.sol
require(msg.sender == owner, "You is not owner");
function setStakeDec(uint _count) external onlyOwner { stakeDec = _count; }
12,311,339
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import {ReentrancyGuard} from "@rari-capital/solmate/src/utils/ReentrancyGuard.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {ERC721TransferHelper} from "../../../../transferHelpers/ERC721TransferHelper.sol"; import {FeePayoutSupportV1} from "../../../../common/FeePayoutSupport/FeePayoutSupportV1.sol"; import {ModuleNamingSupportV1} from "../../../../common/ModuleNamingSupport/ModuleNamingSupportV1.sol"; import {IReserveAuctionFindersEth} from "./IReserveAuctionFindersEth.sol"; /// @title Reserve Auction Finders ETH /// @author kulkarohan /// @notice Module adding Finders Fee to Reserve Auction Core ETH contract ReserveAuctionFindersEth is IReserveAuctionFindersEth, ReentrancyGuard, FeePayoutSupportV1, ModuleNamingSupportV1 { /// @notice The minimum amount of time left in an auction after a new bid is created uint16 constant TIME_BUFFER = 15 minutes; /// @notice The minimum percentage difference between two bids uint8 constant MIN_BID_INCREMENT_PERCENTAGE = 10; /// @notice The ZORA ERC-721 Transfer Helper ERC721TransferHelper public immutable erc721TransferHelper; /// @notice The auction for a given NFT, if one exists /// @dev ERC-721 token contract => ERC-721 token id => Auction mapping(address => mapping(uint256 => Auction)) public auctionForNFT; /// @notice The metadata for a given auction /// @param seller The address of the seller /// @param reservePrice The reserve price to start the auction /// @param sellerFundsRecipient The address where funds are sent after the auction /// @param highestBid The highest bid of the auction /// @param highestBidder The address of the highest bidder /// @param duration The length of time that the auction runs after the first bid is placed /// @param startTime The time that the first bid can be placed /// @param finder The address that referred the highest bid /// @param firstBidTime The time that the first bid is placed /// @param findersFeeBps The fee that is sent to the referrer of the highest bid struct Auction { address seller; uint96 reservePrice; address sellerFundsRecipient; uint96 highestBid; address highestBidder; uint48 duration; uint48 startTime; address finder; uint80 firstBidTime; uint16 findersFeeBps; } /// @notice Emitted when an auction is created /// @param tokenContract The ERC-721 token address of the created auction /// @param tokenId The ERC-721 token id of the created auction /// @param auction The metadata of the created auction event AuctionCreated(address indexed tokenContract, uint256 indexed tokenId, Auction auction); /// @notice Emitted when a reserve price is updated /// @param tokenContract The ERC-721 token address of the updated auction /// @param tokenId The ERC-721 token id of the updated auction /// @param auction The metadata of the updated auction event AuctionReservePriceUpdated(address indexed tokenContract, uint256 indexed tokenId, Auction auction); /// @notice Emitted when an auction is canceled /// @param tokenContract The ERC-721 token address of the canceled auction /// @param tokenId The ERC-721 token id of the canceled auction /// @param auction The metadata of the canceled auction event AuctionCanceled(address indexed tokenContract, uint256 indexed tokenId, Auction auction); /// @notice Emitted when a bid is placed /// @param tokenContract The ERC-721 token address of the auction /// @param tokenId The ERC-721 token id of the auction /// @param firstBid If the bid started the auction /// @param extended If the bid extended the auction /// @param auction The metadata of the auction event AuctionBid(address indexed tokenContract, uint256 indexed tokenId, bool firstBid, bool extended, Auction auction); /// @notice Emitted when an auction has ended /// @param tokenContract The ERC-721 token address of the auction /// @param tokenId The ERC-721 token id of the auction /// @param auction The metadata of the settled auction event AuctionEnded(address indexed tokenContract, uint256 indexed tokenId, Auction auction); /// @param _erc721TransferHelper The ZORA ERC-721 Transfer Helper address /// @param _royaltyEngine The Manifold Royalty Engine address /// @param _protocolFeeSettings The ZORA Protocol Fee Settings address /// @param _weth The WETH token address constructor( address _erc721TransferHelper, address _royaltyEngine, address _protocolFeeSettings, address _weth ) FeePayoutSupportV1(_royaltyEngine, _protocolFeeSettings, _weth, ERC721TransferHelper(_erc721TransferHelper).ZMM().registrar()) ModuleNamingSupportV1("Reserve Auction Finders ETH") { erc721TransferHelper = ERC721TransferHelper(_erc721TransferHelper); } /// @notice Implements EIP-165 for standard interface detection /// @dev `0x01ffc9a7` is the IERC165 interface id /// @param _interfaceId The identifier of a given interface /// @return If the given interface is supported function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == type(IReserveAuctionFindersEth).interfaceId || _interfaceId == 0x01ffc9a7; } // ,-. // `-' // /|\ // | ,------------------------. // / \ |ReserveAuctionFindersEth| // Caller `-----------+------------' // | createAuction() | // | -------------------------> // | | // | |----. // | | | store auction metadata // | |<---' // | | // | |----. // | | | emit AuctionCreated() // | |<---' // Caller ,-----------+------------. // ,-. |ReserveAuctionFindersEth| // `-' `------------------------' // /|\ // | // / \ /// @notice Creates an auction for a given NFT /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token /// @param _duration The length of time the auction should run after the first bid /// @param _reservePrice The minimum bid amount to start the auction /// @param _sellerFundsRecipient The address to send funds to once the auction is complete /// @param _startTime The time that users can begin placing bids /// @param _findersFeeBps The fee to send to the referrer of the winning bid function createAuction( address _tokenContract, uint256 _tokenId, uint256 _duration, uint256 _reservePrice, address _sellerFundsRecipient, uint256 _startTime, uint256 _findersFeeBps ) external nonReentrant { // Get the owner of the specified token address tokenOwner = IERC721(_tokenContract).ownerOf(_tokenId); // Ensure the caller is the owner or an approved operator require(msg.sender == tokenOwner || IERC721(_tokenContract).isApprovedForAll(tokenOwner, msg.sender), "ONLY_TOKEN_OWNER_OR_OPERATOR"); // Ensure the funds recipient is specified require(_sellerFundsRecipient != address(0), "INVALID_FUNDS_RECIPIENT"); // Ensure the finders fee does not exceed 10,000 basis points require(_findersFeeBps <= 10000, "INVALID_FINDERS_FEE"); // Store the auction metadata auctionForNFT[_tokenContract][_tokenId].seller = tokenOwner; auctionForNFT[_tokenContract][_tokenId].reservePrice = uint96(_reservePrice); auctionForNFT[_tokenContract][_tokenId].sellerFundsRecipient = _sellerFundsRecipient; auctionForNFT[_tokenContract][_tokenId].duration = uint48(_duration); auctionForNFT[_tokenContract][_tokenId].startTime = uint48(_startTime); auctionForNFT[_tokenContract][_tokenId].findersFeeBps = uint16(_findersFeeBps); emit AuctionCreated(_tokenContract, _tokenId, auctionForNFT[_tokenContract][_tokenId]); } // ,-. // `-' // /|\ // | ,------------------------. // / \ |ReserveAuctionFindersEth| // Caller `-----------+------------' // | setAuctionReservePrice() | // | -------------------------> // | | // | |----. // | | | update reserve price // | |<---' // | | // | |----. // | | | emit AuctionReservePriceUpdated() // | |<---' // Caller ,-----------+------------. // ,-. |ReserveAuctionFindersEth| // `-' `------------------------' // /|\ // | // / \ /// @notice Updates the reserve price for a given auction /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token /// @param _reservePrice The new reserve price function setAuctionReservePrice( address _tokenContract, uint256 _tokenId, uint256 _reservePrice ) external nonReentrant { // Get the auction for the specified token Auction storage auction = auctionForNFT[_tokenContract][_tokenId]; // Ensure the auction has not started require(auction.firstBidTime == 0, "AUCTION_STARTED"); // Ensure the caller is the seller require(msg.sender == auction.seller, "ONLY_SELLER"); // Update the reserve price auction.reservePrice = uint96(_reservePrice); emit AuctionReservePriceUpdated(_tokenContract, _tokenId, auction); } // ,-. // `-' // /|\ // | ,------------------------. // / \ |ReserveAuctionFindersEth| // Caller `-----------+------------' // | cancelAuction() | // | -------------------------> // | | // | |----. // | | | emit AuctionCanceled() // | |<---' // | | // | |----. // | | | delete auction // | |<---' // Caller ,-----------+------------. // ,-. |ReserveAuctionFindersEth| // `-' `------------------------' // /|\ // | // / \ /// @notice Cancels the auction for a given NFT /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token function cancelAuction(address _tokenContract, uint256 _tokenId) external nonReentrant { // Get the auction for the specified token Auction memory auction = auctionForNFT[_tokenContract][_tokenId]; // Ensure the auction has not started require(auction.firstBidTime == 0, "AUCTION_STARTED"); // Ensure the caller is the seller or a new owner of the token require(msg.sender == auction.seller || msg.sender == IERC721(_tokenContract).ownerOf(_tokenId), "ONLY_SELLER_OR_TOKEN_OWNER"); emit AuctionCanceled(_tokenContract, _tokenId, auction); // Remove the auction from storage delete auctionForNFT[_tokenContract][_tokenId]; } // ,-. // `-' // /|\ // | ,------------------------. ,--------------------. // / \ |ReserveAuctionFindersEth| |ERC721TransferHelper| // Caller `-----------+------------' `---------+----------' // | createBid() | | // | -------------------------> | // | | | // | | | // | ___________________________________________________________________ // | ! ALT / First bid? | | ! // | !_____/ | | ! // | ! |----. | ! // | ! | | start auction | ! // | ! |<---' | ! // | ! | | ! // | ! |----. | ! // | ! | | transferFrom() | ! // | ! |<---' | ! // | ! | | ! // | ! |----. ! // | ! | | transfer NFT from seller to escrow ! // | ! |<---' ! // | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! // | ! [refund previous bidder] | ! // | ! |----. | ! // | ! | | transfer ETH to bidder | ! // | ! |<---' | ! // | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! // | | | // | | | // | _______________________________________________ | // | ! ALT / Bid placed within 15 min of end? ! | // | !_____/ | ! | // | ! |----. ! | // | ! | | extend auction ! | // | ! |<---' ! | // | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | // | !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | // | | | // | |----. | // | | | emit AuctionBid() | // | |<---' | // Caller ,-----------+------------. ,---------+----------. // ,-. |ReserveAuctionFindersEth| |ERC721TransferHelper| // `-' `------------------------' `--------------------' // /|\ // | // / \ /// @notice Places a bid on the auction for a given NFT /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token /// @param _finder The referrer of the bid function createBid( address _tokenContract, uint256 _tokenId, address _finder ) external payable nonReentrant { // Get the auction for the specified token Auction storage auction = auctionForNFT[_tokenContract][_tokenId]; // Cache the seller address seller = auction.seller; // Ensure the auction exists require(seller != address(0), "AUCTION_DOES_NOT_EXIST"); // Ensure the auction has started or is valid to start require(block.timestamp >= auction.startTime, "AUCTION_NOT_STARTED"); // Cache more auction metadata uint256 firstBidTime = auction.firstBidTime; uint256 duration = auction.duration; // Used to emit whether the bid started the auction bool firstBid; // If this is the first bid, start the auction if (firstBidTime == 0) { // Ensure the bid meets the reserve price require(msg.value >= auction.reservePrice, "RESERVE_PRICE_NOT_MET"); // Store the current time as the first bid time auction.firstBidTime = uint80(block.timestamp); // Mark this bid as the first firstBid = true; // Transfer the NFT from the seller into escrow for the duration of the auction // Reverts if the seller did not approve the ERC721TransferHelper or no longer owns the token erc721TransferHelper.transferFrom(_tokenContract, seller, address(this), _tokenId); // Else this is a subsequent bid, so refund the previous bidder } else { // Ensure the auction has not ended require(block.timestamp < (firstBidTime + duration), "AUCTION_OVER"); // Cache the highest bid uint256 highestBid = auction.highestBid; // Used to store the minimum bid required to outbid the highest bidder uint256 minValidBid; // Calculate the minimum bid required (10% higher than the highest bid) // Cannot overflow as the highest bid would have to be magnitudes higher than the total supply of ETH unchecked { minValidBid = highestBid + ((highestBid * MIN_BID_INCREMENT_PERCENTAGE) / 100); } // Ensure the incoming bid meets the minimum require(msg.value >= minValidBid, "MINIMUM_BID_NOT_MET"); // Refund the previous bidder _handleOutgoingTransfer(auction.highestBidder, highestBid, address(0), 50000); } // Store the attached ETH as the highest bid auction.highestBid = uint96(msg.value); // Store the caller as the highest bidder auction.highestBidder = msg.sender; // Store the finder of the bid auction.finder = _finder; // Used to emit whether the bid extended the auction bool extended; // Used to store the auction time remaining uint256 timeRemaining; // Get the auction time remaining // Cannot underflow as `firstBidTime + duration` is ensured to be greater than `block.timestamp` unchecked { timeRemaining = firstBidTime + duration - block.timestamp; } // If the bid is placed within 15 minutes of the auction end, extend the auction if (timeRemaining < TIME_BUFFER) { // Add (15 minutes - remaining time) to the duration so that 15 minutes remain // Cannot underflow as `timeRemaining` is ensured to be less than `TIME_BUFFER` unchecked { auction.duration += uint48(TIME_BUFFER - timeRemaining); } // Mark the bid as one that extended the auction extended = true; } emit AuctionBid(_tokenContract, _tokenId, firstBid, extended, auction); } // ,-. // `-' // /|\ // | ,------------------------. // / \ |ReserveAuctionFindersEth| // Caller `-----------+------------' // | settleAuction() | // | -------------------------> // | | // | |----. // | | | validate auction ended // | |<---' // | | // | |----. // | | | handle royalty payouts // | |<---' // | | // | | // | __________________________________________________________ // | ! ALT / finders fee configured for this auction? ! // | !_____/ | ! // | ! |----. ! // | ! | | handle finders fee payout ! // | ! |<---' ! // | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! // | !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! // | | // | |----. // | | | handle seller funds recipient payout // | |<---' // | | // | |----. // | | | transfer NFT from escrow to winning bidder // | |<---' // | | // | |----. // | | | emit AuctionEnded() // | |<---' // | | // | |----. // | | | delete auction from contract // | |<---' // Caller ,-----------+------------. // ,-. |ReserveAuctionFindersEth| // `-' `------------------------' // /|\ // | // / \ /// @notice Ends the auction for a given NFT /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token function settleAuction(address _tokenContract, uint256 _tokenId) external nonReentrant { // Get the auction for the specified token Auction memory auction = auctionForNFT[_tokenContract][_tokenId]; // Cache the time of the first bid uint256 firstBidTime = auction.firstBidTime; // Ensure the auction had started require(firstBidTime != 0, "AUCTION_NOT_STARTED"); // Ensure the auction has ended require(block.timestamp >= (firstBidTime + auction.duration), "AUCTION_NOT_OVER"); // Payout associated token royalties, if any (uint256 remainingProfit, ) = _handleRoyaltyPayout(_tokenContract, _tokenId, auction.highestBid, address(0), 300000); // Payout the module fee, if configured by the owner remainingProfit = _handleProtocolFeePayout(remainingProfit, address(0)); // Cache the finder of the winning bid address finder = auction.finder; // Payout the finder, if referred if (finder != address(0)) { // Get the fee from the remaining profit uint256 finderFee = (remainingProfit * auction.findersFeeBps) / 10000; // Transfer the amount to the finder _handleOutgoingTransfer(finder, finderFee, address(0), 50000); // Update the remaining profit remainingProfit -= finderFee; } // Transfer the remaining profit to the funds recipient _handleOutgoingTransfer(auction.sellerFundsRecipient, remainingProfit, address(0), 50000); // Transfer the NFT to the winning bidder IERC721(_tokenContract).transferFrom(address(this), auction.highestBidder, _tokenId); emit AuctionEnded(_tokenContract, _tokenId, auction); // Remove the auction from storage delete auctionForNFT[_tokenContract][_tokenId]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Gas optimized reentrancy protection for smart contracts. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol) abstract contract ReentrancyGuard { uint256 private reentrancyStatus = 1; modifier nonReentrant() { require(reentrancyStatus == 1, "REENTRANCY"); reentrancyStatus = 2; _; reentrancyStatus = 1; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {BaseTransferHelper} from "./BaseTransferHelper.sol"; /// @title ERC-721 Transfer Helper /// @author tbtstl <[email protected]> /// @notice This contract provides modules the ability to transfer ZORA user ERC-721s with their permission contract ERC721TransferHelper is BaseTransferHelper { constructor(address _approvalsManager) BaseTransferHelper(_approvalsManager) {} function safeTransferFrom( address _token, address _from, address _to, uint256 _tokenId ) public onlyApprovedModule(_from) { IERC721(_token).safeTransferFrom(_from, _to, _tokenId); } function transferFrom( address _token, address _from, address _to, uint256 _tokenId ) public onlyApprovedModule(_from) { IERC721(_token).transferFrom(_from, _to, _tokenId); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import {IRoyaltyEngineV1} from "@manifoldxyz/royalty-registry-solidity/contracts/IRoyaltyEngineV1.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import {ZoraProtocolFeeSettings} from "../../auxiliary/ZoraProtocolFeeSettings/ZoraProtocolFeeSettings.sol"; import {OutgoingTransferSupportV1} from "../OutgoingTransferSupport/V1/OutgoingTransferSupportV1.sol"; /// @title FeePayoutSupportV1 /// @author tbtstl <[email protected]> /// @notice This contract extension supports paying out protocol fees and royalties contract FeePayoutSupportV1 is OutgoingTransferSupportV1 { /// @notice The ZORA Module Registrar address public immutable registrar; /// @notice The ZORA Protocol Fee Settings ZoraProtocolFeeSettings immutable protocolFeeSettings; /// @notice The Manifold Royalty Engine IRoyaltyEngineV1 royaltyEngine; /// @notice Emitted when royalties are paid /// @param tokenContract The ERC-721 token address of the royalty payout /// @param tokenId The ERC-721 token ID of the royalty payout /// @param recipient The recipient address of the royalty /// @param amount The amount paid to the recipient event RoyaltyPayout(address indexed tokenContract, uint256 indexed tokenId, address recipient, uint256 amount); /// @param _royaltyEngine The Manifold Royalty Engine V1 address /// @param _protocolFeeSettings The ZoraProtocolFeeSettingsV1 address /// @param _wethAddress WETH address /// @param _registrarAddress The Registrar address, who can update the royalty engine address constructor( address _royaltyEngine, address _protocolFeeSettings, address _wethAddress, address _registrarAddress ) OutgoingTransferSupportV1(_wethAddress) { royaltyEngine = IRoyaltyEngineV1(_royaltyEngine); protocolFeeSettings = ZoraProtocolFeeSettings(_protocolFeeSettings); registrar = _registrarAddress; } /// @notice Update the address of the Royalty Engine, in case of unexpected update on Manifold's Proxy /// @dev emergency use only – requires a frozen RoyaltyEngineV1 at commit 4ae77a73a8a73a79d628352d206fadae7f8e0f74 /// to be deployed elsewhere, or a contract matching that ABI /// @param _royaltyEngine The address for the new royalty engine function setRoyaltyEngineAddress(address _royaltyEngine) public { require(msg.sender == registrar, "setRoyaltyEngineAddress only registrar"); require( ERC165Checker.supportsInterface(_royaltyEngine, type(IRoyaltyEngineV1).interfaceId), "setRoyaltyEngineAddress must match IRoyaltyEngineV1 interface" ); royaltyEngine = IRoyaltyEngineV1(_royaltyEngine); } /// @notice Pays out the protocol fee to its fee recipient /// @param _amount The sale amount /// @param _payoutCurrency The currency to pay the fee /// @return The remaining funds after paying the protocol fee function _handleProtocolFeePayout(uint256 _amount, address _payoutCurrency) internal returns (uint256) { // Get fee for this module uint256 protocolFee = protocolFeeSettings.getFeeAmount(address(this), _amount); // If no fee, return initial amount if (protocolFee == 0) return _amount; // Get fee recipient (, address feeRecipient) = protocolFeeSettings.moduleFeeSetting(address(this)); // Payout protocol fee _handleOutgoingTransfer(feeRecipient, protocolFee, _payoutCurrency, 50000); // Return remaining amount return _amount - protocolFee; } /// @notice Pays out royalties for given NFTs /// @param _tokenContract The NFT contract address to get royalty information from /// @param _tokenId, The Token ID to get royalty information from /// @param _amount The total sale amount /// @param _payoutCurrency The ERC-20 token address to payout royalties in, or address(0) for ETH /// @param _gasLimit The gas limit to use when attempting to payout royalties. Uses gasleft() if not provided. /// @return The remaining funds after paying out royalties function _handleRoyaltyPayout( address _tokenContract, uint256 _tokenId, uint256 _amount, address _payoutCurrency, uint256 _gasLimit ) internal returns (uint256, bool) { // If no gas limit was provided or provided gas limit greater than gas left, just pass the remaining gas. uint256 gas = (_gasLimit == 0 || _gasLimit > gasleft()) ? gasleft() : _gasLimit; // External call ensuring contract doesn't run out of gas paying royalties try this._handleRoyaltyEnginePayout{gas: gas}(_tokenContract, _tokenId, _amount, _payoutCurrency) returns (uint256 remainingFunds) { // Return remaining amount if royalties payout succeeded return (remainingFunds, true); } catch { // Return initial amount if royalties payout failed return (_amount, false); } } /// @notice Pays out royalties for NFTs based on the information returned by the royalty engine /// @dev This method is external to enable setting a gas limit when called - see `_handleRoyaltyPayout`. /// @param _tokenContract The NFT Contract to get royalty information from /// @param _tokenId, The Token ID to get royalty information from /// @param _amount The total sale amount /// @param _payoutCurrency The ERC-20 token address to payout royalties in, or address(0) for ETH /// @return The remaining funds after paying out royalties function _handleRoyaltyEnginePayout( address _tokenContract, uint256 _tokenId, uint256 _amount, address _payoutCurrency ) external payable returns (uint256) { // Ensure the caller is the contract require(msg.sender == address(this), "_handleRoyaltyEnginePayout only self callable"); // Get the royalty recipients and their associated amounts (address payable[] memory recipients, uint256[] memory amounts) = royaltyEngine.getRoyalty(_tokenContract, _tokenId, _amount); // Store the number of recipients uint256 numRecipients = recipients.length; // If there are no royalties, return the initial amount if (numRecipients == 0) return _amount; // Store the initial amount uint256 amountRemaining = _amount; // Store the variables that cache each recipient and amount address recipient; uint256 amount; // Payout each royalty for (uint256 i = 0; i < numRecipients; ) { // Cache the recipient and amount recipient = recipients[i]; amount = amounts[i]; // Ensure that we aren't somehow paying out more than we have require(amountRemaining >= amount, "insolvent"); // Transfer to the recipient _handleOutgoingTransfer(recipient, amount, _payoutCurrency, 50000); emit RoyaltyPayout(_tokenContract, _tokenId, recipient, amount); // Cannot underflow as remaining amount is ensured to be greater than or equal to royalty amount unchecked { amountRemaining -= amount; ++i; } } return amountRemaining; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; /// @title Module Naming Support V1 /// @author kulkarohan <[email protected]> /// @notice This contract extension supports naming modules contract ModuleNamingSupportV1 { /// @notice The module name string public name; /// @notice Sets the name of a module /// @param _name The module name to set constructor(string memory _name) { name = _name; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; /// @title IReserveAuctionFindersEth /// @author kulkarohan /// @notice Interface for Reserve Auction Finders ETH interface IReserveAuctionFindersEth { /// @notice Creates an auction for a given NFT /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token /// @param _duration The length of time the auction should run after the first bid /// @param _reservePrice The minimum bid amount to start the auction /// @param _sellerFundsRecipient The address to send funds to once the auction is complete /// @param _startTime The time that users can begin placing bids /// @param _findersFeeBps The fee to send to the referrer of the winning bid function createAuction( address _tokenContract, uint256 _tokenId, uint256 _duration, uint256 _reservePrice, address _sellerFundsRecipient, uint256 _startTime, uint256 _findersFeeBps ) external; /// @notice Updates the reserve price for a given auction /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token /// @param _reservePrice The new reserve price function setAuctionReservePrice( address _tokenContract, uint256 _tokenId, uint256 _reservePrice ) external; /// @notice Cancels the auction for a given NFT /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token function cancelAuction(address _tokenContract, uint256 _tokenId) external; /// @notice Places a bid on the auction for a given NFT /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token /// @param _finder The referrer of the bid function createBid( address _tokenContract, uint256 _tokenId, address _finder ) external payable; /// @notice Ends the auction for a given NFT /// @param _tokenContract The address of the ERC-721 token /// @param _tokenId The id of the ERC-721 token function settleAuction(address _tokenContract, uint256 _tokenId) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import {ZoraModuleManager} from "../ZoraModuleManager.sol"; /// @title Base Transfer Helper /// @author tbtstl <[email protected]> /// @notice This contract provides shared utility for ZORA transfer helpers contract BaseTransferHelper { /// @notice The ZORA Module Manager ZoraModuleManager public immutable ZMM; /// @param _moduleManager The ZORA Module Manager referred to for transfer permissions constructor(address _moduleManager) { require(_moduleManager != address(0), "must set module manager to non-zero address"); ZMM = ZoraModuleManager(_moduleManager); } /// @notice Ensures a user has approved the module they're calling /// @param _user The address of the user modifier onlyApprovedModule(address _user) { require(isModuleApproved(_user), "module has not been approved by user"); _; } /// @notice If a user has approved the module they're calling /// @param _user The address of the user function isModuleApproved(address _user) public view returns (bool) { return ZMM.isModuleApproved(_user, msg.sender); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import {ZoraProtocolFeeSettings} from "./auxiliary/ZoraProtocolFeeSettings/ZoraProtocolFeeSettings.sol"; /// @title ZoraModuleManager /// @author tbtstl <[email protected]> /// @notice This contract allows users to approve registered modules on ZORA V3 contract ZoraModuleManager { /// @notice The EIP-712 type for a signed approval /// @dev keccak256("SignedApproval(address module,address user,bool approved,uint256 deadline,uint256 nonce)") bytes32 private constant SIGNED_APPROVAL_TYPEHASH = 0x8413132cc7aa5bd2ce1a1b142a3f09e2baeda86addf4f9a5dacd4679f56e7cec; /// @notice The EIP-712 domain separator bytes32 private immutable EIP_712_DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes("ZORA")), keccak256(bytes("3")), _chainID(), address(this) ) ); /// @notice The module fee NFT contract to mint from upon module registration ZoraProtocolFeeSettings public immutable moduleFeeToken; /// @notice The registrar address that can register modules address public registrar; /// @notice Mapping of users and modules to approved status /// @dev User address => Module address => Approved mapping(address => mapping(address => bool)) public userApprovals; /// @notice Mapping of modules to registered status /// @dev Module address => Registered mapping(address => bool) public moduleRegistered; /// @notice The signature nonces for 3rd party module approvals mapping(address => uint256) public sigNonces; /// @notice Ensures only the registrar can register modules modifier onlyRegistrar() { require(msg.sender == registrar, "ZMM::onlyRegistrar must be registrar"); _; } /// @notice Emitted when a user's module approval is updated /// @param user The address of the user /// @param module The address of the module /// @param approved Whether the user added or removed approval event ModuleApprovalSet(address indexed user, address indexed module, bool approved); /// @notice Emitted when a module is registered /// @param module The address of the module event ModuleRegistered(address indexed module); /// @notice Emitted when the registrar address is updated /// @param newRegistrar The address of the new registrar event RegistrarChanged(address indexed newRegistrar); /// @param _registrar The initial registrar for the manager /// @param _feeToken The module fee token contract to mint from upon module registration constructor(address _registrar, address _feeToken) { require(_registrar != address(0), "ZMM::must set registrar to non-zero address"); registrar = _registrar; moduleFeeToken = ZoraProtocolFeeSettings(_feeToken); } /// @notice Returns true if the user has approved a given module, false otherwise /// @param _user The user to check approvals for /// @param _module The module to check approvals for /// @return True if the module has been approved by the user, false otherwise function isModuleApproved(address _user, address _module) external view returns (bool) { return userApprovals[_user][_module]; } // ,-. // `-' // /|\ // | ,-----------------. // / \ |ZoraModuleManager| // Caller `--------+--------' // | setApprovalForModule()| // | ----------------------> // | | // | |----. // | | | set approval for module // | |<---' // | | // | |----. // | | | emit ModuleApprovalSet() // | |<---' // Caller ,--------+--------. // ,-. |ZoraModuleManager| // `-' `-----------------' // /|\ // | // / \ /// @notice Allows a user to set the approval for a given module /// @param _module The module to approve /// @param _approved A boolean, whether or not to approve a module function setApprovalForModule(address _module, bool _approved) public { _setApprovalForModule(_module, msg.sender, _approved); } // ,-. // `-' // /|\ // | ,-----------------. // / \ |ZoraModuleManager| // Caller `--------+--------' // | setBatchApprovalForModule()| // | ---------------------------> // | | // | | // | _____________________________________________________ // | ! LOOP / for each module ! // | !______/ | ! // | ! |----. ! // | ! | | set approval for module ! // | ! |<---' ! // | ! | ! // | ! |----. ! // | ! | | emit ModuleApprovalSet() ! // | ! |<---' ! // | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! // Caller ,--------+--------. // ,-. |ZoraModuleManager| // `-' `-----------------' // /|\ // | // / \ /// @notice Sets approvals for multiple modules at once /// @param _modules The list of module addresses to set approvals for /// @param _approved A boolean, whether or not to approve the modules function setBatchApprovalForModules(address[] memory _modules, bool _approved) public { // Store the number of module addresses provided uint256 numModules = _modules.length; // Loop through each address for (uint256 i = 0; i < numModules; ) { // Ensure that it's a registered module and set the approval _setApprovalForModule(_modules[i], msg.sender, _approved); // Cannot overflow as array length cannot exceed uint256 max unchecked { ++i; } } } // ,-. // `-' // /|\ // | ,-----------------. // / \ |ZoraModuleManager| // Caller `--------+--------' // | setApprovalForModuleBySig()| // | ---------------------------> // | | // | |----. // | | | recover user address from signature // | |<---' // | | // | |----. // | | | set approval for module // | |<---' // | | // | |----. // | | | emit ModuleApprovalSet() // | |<---' // Caller ,--------+--------. // ,-. |ZoraModuleManager| // `-' `-----------------' // /|\ // | // / \ /// @notice Sets approval for a module given an EIP-712 signature /// @param _module The module to approve /// @param _user The user to approve the module for /// @param _approved A boolean, whether or not to approve a module /// @param _deadline The deadline at which point the given signature expires /// @param _v The 129th byte and chain ID of the signature /// @param _r The first 64 bytes of the signature /// @param _s Bytes 64-128 of the signature function setApprovalForModuleBySig( address _module, address _user, bool _approved, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) public { require(_deadline == 0 || _deadline >= block.timestamp, "ZMM::setApprovalForModuleBySig deadline expired"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", EIP_712_DOMAIN_SEPARATOR, keccak256(abi.encode(SIGNED_APPROVAL_TYPEHASH, _module, _user, _approved, _deadline, sigNonces[_user]++)) ) ); address recoveredAddress = ecrecover(digest, _v, _r, _s); require(recoveredAddress != address(0) && recoveredAddress == _user, "ZMM::setApprovalForModuleBySig invalid signature"); _setApprovalForModule(_module, _user, _approved); } // ,-. // `-' // /|\ // | ,-----------------. ,-----------------------. // / \ |ZoraModuleManager| |ZoraProtocolFeeSettings| // Registrar `--------+--------' `-----------+-----------' // | registerModule() | | // |----------------------->| | // | | | // | ----. | // | | register module | // | <---' | // | | | // | | mint() | // | |------------------------------>| // | | | // | | ----. // | | | mint token to registrar // | | <---' // | | | // | ----. | // | | emit ModuleRegistered() | // | <---' | // Registrar ,--------+--------. ,-----------+-----------. // ,-. |ZoraModuleManager| |ZoraProtocolFeeSettings| // `-' `-----------------' `-----------------------' // /|\ // | // / \ /// @notice Registers a module /// @param _module The address of the module function registerModule(address _module) public onlyRegistrar { require(!moduleRegistered[_module], "ZMM::registerModule module already registered"); moduleRegistered[_module] = true; moduleFeeToken.mint(registrar, _module); emit ModuleRegistered(_module); } // ,-. // `-' // /|\ // | ,-----------------. // / \ |ZoraModuleManager| // Registrar `--------+--------' // | setRegistrar() | // |----------------------->| // | | // | ----. // | | set registrar // | <---' // | | // | ----. // | | emit RegistrarChanged() // | <---' // Registrar ,--------+--------. // ,-. |ZoraModuleManager| // `-' `-----------------' // /|\ // | // / \ /// @notice Sets the registrar for the ZORA Module Manager /// @param _registrar the address of the new registrar function setRegistrar(address _registrar) public onlyRegistrar { require(_registrar != address(0), "ZMM::setRegistrar must set registrar to non-zero address"); registrar = _registrar; emit RegistrarChanged(_registrar); } /// @notice Updates a module approval for a user /// @param _module The address of the module /// @param _user The address of the user /// @param _approved Whether the user is adding or removing approval function _setApprovalForModule( address _module, address _user, bool _approved ) private { require(moduleRegistered[_module], "ZMM::must be registered module"); userApprovals[_user][_module] = _approved; emit ModuleApprovalSet(msg.sender, _module, _approved); } /// @notice The EIP-155 chain id function _chainID() private view returns (uint256 id) { assembly { id := chainid() } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; interface IERC721TokenURI { function tokenURI(uint256 tokenId) external view returns (string memory); } /// @title ZoraProtocolFeeSettings /// @author tbtstl <[email protected]> /// @notice This contract allows an optional fee percentage and recipient to be set for individual ZORA modules contract ZoraProtocolFeeSettings is ERC721 { /// @notice The address of the contract metadata address public metadata; /// @notice The address of the contract owner address public owner; /// @notice The address of the ZORA Module Manager address public minter; /// @notice The metadata of a module fee setting /// @param feeBps The basis points fee /// @param feeRecipient The recipient of the fee struct FeeSetting { uint16 feeBps; address feeRecipient; } /// @notice Mapping of modules to fee settings /// @dev Module address => FeeSetting mapping(address => FeeSetting) public moduleFeeSetting; /// @notice Ensures only the owner of a module fee NFT can set its fee /// @param _module The address of the module modifier onlyModuleOwner(address _module) { uint256 tokenId = moduleToTokenId(_module); require(ownerOf(tokenId) == msg.sender, "onlyModuleOwner"); _; } /// @notice Emitted when the fee for a module is updated /// @param module The address of the module /// @param feeRecipient The address of the fee recipient /// @param feeBps The basis points of the fee event ProtocolFeeUpdated(address indexed module, address feeRecipient, uint16 feeBps); /// @notice Emitted when the contract metadata is updated /// @param newMetadata The address of the new metadata event MetadataUpdated(address indexed newMetadata); /// @notice Emitted when the contract owner is updated /// @param newOwner The address of the new owner event OwnerUpdated(address indexed newOwner); constructor() ERC721("ZORA Module Fee Switch", "ZORF") { _setOwner(msg.sender); } /// @notice Initialize the Protocol Fee Settings /// @param _minter The address that can mint new NFTs (expected ZoraModuleManager address) function init(address _minter, address _metadata) external { require(msg.sender == owner, "init only owner"); require(minter == address(0), "init already initialized"); minter = _minter; metadata = _metadata; } // ,-. // `-' // /|\ // | ,-----------------------. // / \ |ZoraProtocolFeeSettings| // Minter `-----------+-----------' // | mint() | // | ------------------------>| // | | // | ----. // | | derive token ID from module address // | <---' // | | // | ----. // | | mint token to given address // | <---' // | | // | return token ID | // | <------------------------| // Minter ,-----------+-----------. // ,-. |ZoraProtocolFeeSettings| // `-' `-----------------------' // /|\ // | // / \ /// @notice Mint a new protocol fee setting for a module /// @param _to The address to send the protocol fee setting token to /// @param _module The module for which the minted token will represent function mint(address _to, address _module) external returns (uint256) { require(msg.sender == minter, "mint onlyMinter"); uint256 tokenId = moduleToTokenId(_module); _mint(_to, tokenId); return tokenId; } // ,-. // `-' // /|\ // | ,-----------------------. // / \ |ZoraProtocolFeeSettings| // ModuleOwner `-----------+-----------' // | setFeeParams() | // |--------------------------->| // | | // | ----. // | | set fee parameters // | <---' // | | // | ----. // | | emit ProtocolFeeUpdated() // | <---' // ModuleOwner ,-----------+-----------. // ,-. |ZoraProtocolFeeSettings| // `-' `-----------------------' // /|\ // | // / \ /// @notice Sets fee parameters for a module fee NFT /// @param _module The module to apply the fee settings to /// @param _feeRecipient The fee recipient address to send fees to /// @param _feeBps The bps of transaction value to send to the fee recipient function setFeeParams( address _module, address _feeRecipient, uint16 _feeBps ) external onlyModuleOwner(_module) { require(_feeBps <= 10000, "setFeeParams must set fee <= 100%"); require(_feeRecipient != address(0) || _feeBps == 0, "setFeeParams fee recipient cannot be 0 address if fee is greater than 0"); moduleFeeSetting[_module] = FeeSetting(_feeBps, _feeRecipient); emit ProtocolFeeUpdated(_module, _feeRecipient, _feeBps); } // ,-. // `-' // /|\ // | ,-----------------------. // / \ |ZoraProtocolFeeSettings| // Owner `-----------+-----------' // | setOwner() | // |------------------------>| // | | // | ----. // | | set owner // | <---' // | | // | ----. // | | emit OwnerUpdated() // | <---' // Owner ,-----------+-----------. // ,-. |ZoraProtocolFeeSettings| // `-' `-----------------------' // /|\ // | // / \ /// @notice Sets the owner of the contract /// @param _owner The address of the owner function setOwner(address _owner) external { require(msg.sender == owner, "setOwner onlyOwner"); _setOwner(_owner); } // ,-. // `-' // /|\ // | ,-----------------------. // / \ |ZoraProtocolFeeSettings| // Owner `-----------+-----------' // | setMetadata() | // |------------------------>| // | | // | ----. // | | set metadata // | <---' // | | // | ----. // | | emit MetadataUpdated() // | <---' // Owner ,-----------+-----------. // ,-. |ZoraProtocolFeeSettings| // `-' `-----------------------' // /|\ // | // / \ /// @notice Sets the metadata of the contract /// @param _metadata The address of the metadata function setMetadata(address _metadata) external { require(msg.sender == owner, "setMetadata onlyOwner"); _setMetadata(_metadata); } /// @notice Computes the fee for a given uint256 amount /// @param _module The module to compute the fee for /// @param _amount The amount to compute the fee for /// @return The amount to be paid out to the fee recipient function getFeeAmount(address _module, uint256 _amount) external view returns (uint256) { return (_amount * moduleFeeSetting[_module].feeBps) / 10000; } /// @notice Returns the module address for a given token ID /// @param _tokenId The token ID /// @return The module address function tokenIdToModule(uint256 _tokenId) public pure returns (address) { return address(uint160(_tokenId)); } /// @notice Returns the token ID for a given module /// @dev We don't worry about losing the top 20 bytes when going from uint256 -> uint160 since we know token ID must have derived from an address /// @param _module The module address /// @return The token ID function moduleToTokenId(address _module) public pure returns (uint256) { return uint256(uint160(_module)); } /// @notice Returns the token URI for a given token ID /// @param _tokenId The token ID /// @return The token URI function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); require(metadata != address(0), "ERC721Metadata: no metadata address"); return IERC721TokenURI(metadata).tokenURI(_tokenId); } /// @notice Sets the contract metadata in `setMetadata` /// @param _metadata The address of the metadata function _setMetadata(address _metadata) private { metadata = _metadata; emit MetadataUpdated(_metadata); } /// @notice Sets the contract owner in `setOwner` /// @param _owner The address of the owner function _setOwner(address _owner) private { owner = _owner; emit OwnerUpdated(_owner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Lookup engine interface */ interface IRoyaltyEngineV1 is IERC165 { /** * Get the royalty for a given token (address, id) and value amount. Does not cache the bps/amounts. Caches the spec for a given token address * * @param tokenAddress - The address of the token * @param tokenId - The id of the token * @param value - The value you wish to get the royalty of * * returns Two arrays of equal length, royalty recipients and the corresponding amount each recipient should get */ function getRoyalty(address tokenAddress, uint256 tokenId, uint256 value) external returns(address payable[] memory recipients, uint256[] memory amounts); /** * View only version of getRoyalty * * @param tokenAddress - The address of the token * @param tokenId - The id of the token * @param value - The value you wish to get the royalty of * * returns Two arrays of equal length, royalty recipients and the corresponding amount each recipient should get */ function getRoyaltyView(address tokenAddress, uint256 tokenId, uint256 value) external view returns(address payable[] memory recipients, uint256[] memory amounts); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IWETH} from "./IWETH.sol"; /// @title OutgoingTransferSupportV1 /// @author tbtstl <[email protected]> /// @notice This contract extension supports paying out funds to an external recipient contract OutgoingTransferSupportV1 { using SafeERC20 for IERC20; IWETH immutable weth; constructor(address _wethAddress) { weth = IWETH(_wethAddress); } /// @notice Handle an outgoing funds transfer /// @dev Wraps ETH in WETH if the receiver cannot receive ETH, noop if the funds to be sent are 0 or recipient is invalid /// @param _dest The destination for the funds /// @param _amount The amount to be sent /// @param _currency The currency to send funds in, or address(0) for ETH /// @param _gasLimit The gas limit to use when attempting a payment (if 0, gasleft() is used) function _handleOutgoingTransfer( address _dest, uint256 _amount, address _currency, uint256 _gasLimit ) internal { if (_amount == 0 || _dest == address(0)) { return; } // Handle ETH payment if (_currency == address(0)) { require(address(this).balance >= _amount, "_handleOutgoingTransfer insolvent"); // If no gas limit was provided or provided gas limit greater than gas left, just use the remaining gas. uint256 gas = (_gasLimit == 0 || _gasLimit > gasleft()) ? gasleft() : _gasLimit; (bool success, ) = _dest.call{value: _amount, gas: gas}(""); // If the ETH transfer fails (sigh), wrap the ETH and try send it as WETH. if (!success) { weth.deposit{value: _amount}(); IERC20(address(weth)).safeTransfer(_dest, _amount); } } else { IERC20(_currency).safeTransfer(_dest, _amount); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; }
IReserveAuctionFindersEth kulkarohan Interface for Reserve Auction Finders ETH
interface IReserveAuctionFindersEth { function createAuction( address _tokenContract, uint256 _tokenId, uint256 _duration, uint256 _reservePrice, address _sellerFundsRecipient, uint256 _startTime, uint256 _findersFeeBps ) external; function setAuctionReservePrice( address _tokenContract, uint256 _tokenId, uint256 _reservePrice ) external; function cancelAuction(address _tokenContract, uint256 _tokenId) external; function createBid( address _tokenContract, uint256 _tokenId, address _finder ) external payable; function settleAuction(address _tokenContract, uint256 _tokenId) external; pragma solidity 0.8.10; }
13,881,389
/* BSD 2-Clause License Copyright (c) 2018, True Names Limited All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ pragma solidity ^0.4.0; import './AbstractENS.sol'; /// @title ENS registry contract, extended with support for parent nodes and time limited uptime /// @author evan GmbH /// @dev based upon ENS from https://github.com/ensdomains/ens/blob/master/contracts/ENSRegistry.sol contract TimedENS is AbstractENS { int256 public validPostExipireWindow = 8 weeks; struct Record { address owner; address resolver; uint64 ttl; bytes32 parent; } mapping(bytes32=>Record) public records; mapping(bytes32=>uint256) public validUntil; /// Permits modifications only by the owner of the specified node. /// @param node node to check modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /// Permits modifications only by the owner of the parent node of a node. /// @param node node to check modifier only_parent_owner(bytes32 node) { if (records[records[node].parent].owner != msg.sender) throw; _; } /// @notice constructs a new TimedENS registrar function TimedENS() { records[0].owner = msg.sender; } /// @notice returns the address that owns the specified node /// @param node namehash of a node /// @return address of node owner function owner(bytes32 node) constant returns(address) { if (isAlive(node, validPostExipireWindow)) { return records[node].owner; } else { return address(0); } } /// @notice returns parent node of given node /// @param node namehash of a node /// @return address of parent node function parent(bytes32 node) constant returns (bytes32) { return records[node].parent; } /// @notice returns the address of resolver the specified node /// @param node namehash of node /// @return address of nodes resolver function resolver(bytes32 node) constant returns(address) { if (isAlive(node, 0)) { return records[node].resolver; } else { return address(0); } } /// @notice returns the TTL of a node, and any records associated with it /// @param node namehash of node /// @return ttl of node value function ttl(bytes32 node) constant returns(uint64) { if (isAlive(node, 0)) { return records[node].ttl; } else { return 0; } } /// @notice transfers ownership of a node to a new address. May only be called by the /// current owner of the node /// @param node node to transfer ownership of /// @param owner address of the new owner function setOwner(bytes32 node, address owner) only_owner(node) { Transfer(node, owner); records[node].owner = owner; } /// @notice transfers ownership of a subnode sha3(node, label) to a new address. May only be /// called by the owner of the parent node /// @param node parent node /// @param label hash of the label specifying the subnode /// @param owner address of the new owner function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) { var subnode = sha3(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; records[subnode].parent = node; } /// @notice sets the resolver address for the specified node /// @param node node to update /// @param resolver address of the resolver function setResolver(bytes32 node, address resolver) only_owner(node) { NewResolver(node, resolver); records[node].resolver = resolver; } /// @notice sets the TTL for the specified node /// @param node node to update /// @param ttl TTL in seconds function setTTL(bytes32 node, uint64 ttl) only_owner(node) { NewTTL(node, ttl); records[node].ttl = ttl; } /// @notice sets duration, that keeps the owner of an expired node after its expiration /// @param newValidPostExipireWindow new value to set function setValidPostExpireWindow(int256 newValidPostExipireWindow) public only_owner(0) { validPostExipireWindow = newValidPostExipireWindow; } /// @notice sets duration, that a given node can be resolved before it expires /// @param node node to set valid until for /// @param value new value to set function setValidUntil(bytes32 node, uint256 value) only_parent_owner(node) { validUntil[node] = value; } /// @notice checks if a given node is still alive shifted by given offset (use offset 0 for /// "now") /// @param hash namehash of node /// @param offset int256 offset to add onto valid until value function isAlive(bytes32 hash, int256 offset) public view returns(bool) { if (validUntil[hash] != 0 && (uint256(int256(validUntil[hash]) + offset) < now)) { // found a set and expired node return false; } else if (hash == bytes32(0)) { // found root node --> valid return true; } else { // check parent return isAlive(records[hash].parent, offset); } } }
sets duration, that keeps the owner of an expired node after its expiration newValidPostExipireWindow new value to set
function setValidPostExpireWindow(int256 newValidPostExipireWindow) public only_owner(0) { validPostExipireWindow = newValidPostExipireWindow; }
12,535,657
//SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "hardhat/console.sol"; import "../ubeswap/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol"; import "../ubeswap/contracts/uniswapv2/interfaces/IUniswapV2Router02SwapOnly.sol"; import "../openzeppelin-solidity/contracts/SafeERC20.sol"; /** * UniswapRouter is a library containing helper functions for interacting with contracts implementing * the IUniswapV2Router02 interface, or subsets of its functionality. **/ library UniswapRouter { using SafeERC20 for IERC20; function swap( IUniswapV2Router02SwapOnly router, address[] memory path, uint256 startTokenBudget, IERC20 startToken, uint256 minAmountOut, uint256 deadline ) internal returns (uint256) { if (path.length >= 2 && startTokenBudget > 0) { startToken.safeIncreaseAllowance(address(router), startTokenBudget); uint256[] memory _swapResultAmounts = router .swapExactTokensForTokens( startTokenBudget, minAmountOut, path, address(this), deadline ); return _swapResultAmounts[_swapResultAmounts.length - 1]; } else { return startTokenBudget; } } function swapTokensForEqualAmounts( IUniswapV2Router02SwapOnly router, uint256[] memory tokenBalances, address[][2][] memory paths, IERC20[] memory startTokens, uint256[2][] memory minAmountsOut, uint256 deadline ) internal returns (uint256, uint256) { uint256 _totalAmountToken0 = 0; uint256 _totalAmountToken1 = 0; for (uint256 i = 0; i < tokenBalances.length; i++) { uint256 _halfTokens = tokenBalances[i] / 2; _totalAmountToken0 += swap( router, paths[i][0], _halfTokens, startTokens[i], minAmountsOut[i][0], deadline ); _totalAmountToken1 += swap( router, paths[i][1], _halfTokens, startTokens[i], minAmountsOut[i][1], deadline ); } return (_totalAmountToken0, _totalAmountToken1); } function addLiquidity( IUniswapV2Router02 router, IERC20 token0, IERC20 token1, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, uint256 deadline ) internal returns ( uint256 amountA, uint256 amountB, uint256 liquidity ) { // Approve the liquidity router to spend the bot's token0/token1 token0.safeIncreaseAllowance(address(router), amount0Desired); token1.safeIncreaseAllowance(address(router), amount1Desired); // Actually add liquidity return router.addLiquidity( address(token0), address(token1), amount0Desired, amount1Desired, amount0Min, amount1Min, address(this), deadline ); } function removeLiquidity( IUniswapV2Router02 router, IERC20 stakingToken, address tokenA, address tokenB, uint256 liquidityAmount, uint256 amountAMin, uint256 amountBMin, address recipient, uint256 deadline ) internal returns (uint256 amountA, uint256 amountB) { stakingToken.safeIncreaseAllowance(address(router), liquidityAmount); return router.removeLiquidity( tokenA, tokenB, liquidityAmount, amountAMin, amountBMin, recipient, deadline ); } }
Approve the liquidity router to spend the bot's token0/token1 Actually add liquidity
function addLiquidity( IUniswapV2Router02 router, IERC20 token0, IERC20 token1, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, uint256 deadline ) internal returns ( uint256 amountA, uint256 amountB, uint256 liquidity ) { token0.safeIncreaseAllowance(address(router), amount0Desired); token1.safeIncreaseAllowance(address(router), amount1Desired); return router.addLiquidity( address(token0), address(token1), amount0Desired, amount1Desired, amount0Min, amount1Min, address(this), deadline ); }
6,359,415
// contracts/MyNFT.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract NFTSimple is ERC721 { constructor() public ERC721("NFTSimple", "NFTS") {} function mint(address to, uint256 tokenId) public { _mint(to, tokenId); } function safeMint(address to, uint256 tokenId) public { _safeMint(to, tokenId); } function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public { safeTransferFrom(from, to, tokenId, data); } // mint a batch of 10 tokens. function batchMint(address to, uint256 number) public{ bytes32 previousBlockHash = blockhash(block.number-1); uint256 startId = uint256(keccak256(abi.encodePacked(previousBlockHash,msg.sender))); for (uint256 i=0;i<number;i++){ safeMint(to,startId+i); } } }
mint a batch of 10 tokens.
function batchMint(address to, uint256 number) public{ bytes32 previousBlockHash = blockhash(block.number-1); uint256 startId = uint256(keccak256(abi.encodePacked(previousBlockHash,msg.sender))); for (uint256 i=0;i<number;i++){ safeMint(to,startId+i); } }
5,408,481
./partial_match/1/0x00000000007767d79f9F4aA1Ff0d71b8E2E4a231/sources/node_modules/@looksrare/contracts-libs/contracts/lowLevelCallers/LowLevelERC20Transfer.sol
Execute ERC20 transferFrom currency Currency address from Sender address to Recipient address amount Amount to transfer/
function _executeERC20TransferFrom(address currency, address from, address to, uint256 amount) internal { if (currency.code.length == 0) { revert NotAContract(); } (bool status, bytes memory data) = currency.call(abi.encodeCall(IERC20.transferFrom, (from, to, amount))); if (!status) { revert ERC20TransferFromFail(); } if (data.length > 0) { if (!abi.decode(data, (bool))) { revert ERC20TransferFromFail(); } } }
16,178,190
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; contract Voting { // Structures struct Voter { bool isRegistered; bool hasVoted; uint votedProposalId; } struct Proposal { string description; uint voteCount; } // vote mapping struct Vote{ // Subject of the vote string tips; // Owner address address owner; // Winner ID uint winningProposalId; // Status ID WorkflowStatus statusId; //Voter mapping mapping (address => Voter) voters; uint votersCount; // Proposal listing Proposal[] proposals; uint maxVoteCount; } // Enumeration enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } mapping (uint => Vote) votes;// Maps use less gas than arrays uint private votesCount;// So a counter is associated to retrive votes // Events event VoteCreated(uint voteIndex); event VoterRegistered(uint voteIndex, address voterAddress); event ProposalsRegistrationStarted(uint voteIndex); event ProposalsRegistrationEnded(uint voteIndex); event ProposalRegistered(uint voteIndex, uint proposalId); event VotingSessionStarted(uint voteIndex); event VotingSessionEnded(uint voteIndex); event Voted (uint voteIndex, address voter, uint proposalId); event VotesTallied(uint voteIndex); event WorkflowStatusChange(uint voteIndex, WorkflowStatus previousStatus, WorkflowStatus newStatus); modifier onlyOwner(uint index){ require(_isOwner(index, msg.sender), '0');//Ownable: caller can be only the owner of the vote _; } modifier onlyRegistered(uint index){ require(votes[index].voters[msg.sender].isRegistered, '1');//Listed: caller has not been registered by the owner _; } // For internal calls, the sender address should be retrived from the top call function _isOwner(uint index, address _address) private view returns (bool) { return votes[index].owner==_address; } modifier onlyRegisteredOrOwner(uint index){ require(votes[index].owner==msg.sender || votes[index].voters[msg.sender].isRegistered, '2');//Ownable or listed only _; } // Setter and interaction functions // // Add a new vote to the list function newVote(string memory tips) external {// Everyone can add a new vote require(bytes(tips).length>0, '3');//Tips should not be empty //didn't accept empty tips votes[votesCount].tips = tips; votes[votesCount].owner = msg.sender; emit VoteCreated(votesCount); votesCount+=1; } // I decided to use only one function insteed of specific status setter like "setProposalsRegistrationStartedStatus" function setNextWorkflowStatus(uint index) external onlyOwner(index){ require(votes[index].statusId != WorkflowStatus.VotesTallied, '4');//The vote is already done // keep the old status for the "WorkflowStatusChange" event. WorkflowStatus oldStatus = votes[index].statusId; // State machine for the status workflow // 0_ Voters registration by the owner. // 0 => 1_ I defined a minimum of two voters, otherwise the vote would not be necessary. // Proposals registration for they registered address. if (votes[index].statusId==WorkflowStatus.RegisteringVoters){ require(votes[index].votersCount>=2, '5');//We should have at least two voters to continue the workflow votes[index].statusId = WorkflowStatus.ProposalsRegistrationStarted; emit ProposalsRegistrationStarted(index); } // 1 => 2_ I defined a minimum of one proposal because it's the minimum to have an outcome. // Close the registration period. else if (votes[index].statusId==WorkflowStatus.ProposalsRegistrationStarted){ require(votes[index].proposals.length>=1, '6');//We should have at least one Proposal to continue the workflow votes[index].statusId = WorkflowStatus.ProposalsRegistrationEnded; emit ProposalsRegistrationEnded(index); } // 2 => 3_ I did not launch the voting session right afterwards to let the voters see the proposals // Open the votes[index]. else if (votes[index].statusId==WorkflowStatus.ProposalsRegistrationEnded){ votes[index].statusId = WorkflowStatus.VotingSessionStarted; emit VotingSessionStarted(index); } // 3 => 4_ Close the vote else if (votes[index].statusId==WorkflowStatus.VotingSessionStarted){ votes[index].statusId = WorkflowStatus.VotingSessionEnded; emit VotingSessionEnded(index); } // 4 => 5_ I did not launch the votes counting right after the VotingSessionEnded because there is two separated points in the exercice. // But all results are publique so the suspense would not be there anyway. else if (votes[index].statusId==WorkflowStatus.VotingSessionEnded){ votes[index].statusId = WorkflowStatus.VotesTallied; emit VotesTallied(index); } emit WorkflowStatusChange(index, oldStatus, votes[index].statusId); } // Let a vote owner to register any etherum address to take part in the votes. function authorize( uint index, address _address) external onlyOwner(index){ require(votes[index].statusId==WorkflowStatus.RegisteringVoters, '7');//Unable to register anyone after the RegisteringVoters workflow status require(votes[index].voters[_address].isRegistered==false, '8');//Address already registered votes[index].voters[_address] = Voter({isRegistered: true, hasVoted: false, votedProposalId: 0}); // The voter counter exists to ensure that there is a minimum of two. votes[index].votersCount++; emit VoterRegistered(index, _address); } // Registered address can add any proposition description at multiple times function newProposal(uint index, string memory description) external onlyRegistered(index){ require(votes[index].statusId==WorkflowStatus.ProposalsRegistrationStarted, '9');//Unable to register any proposals. Proposals Registration not started or already ended votes[index].proposals.push(Proposal({description: description, voteCount:0})); emit ProposalRegistered(index, votes[index].proposals.length-1); } // Registered address can vote once for a registered proposals function doVote(uint index, uint votedProposalId) external onlyRegistered(index){ require(votes[index].statusId==WorkflowStatus.VotingSessionStarted, '10');//Unable to vote while the current workflow status is not VotingSessionStarted require(votes[index].voters[msg.sender].hasVoted==false, '11');//You can t vote twice require(votes[index].proposals.length>votedProposalId, '12');//votedProposalId doesn t exist votes[index].proposals[votedProposalId].voteCount++; votes[index].voters[msg.sender].hasVoted = true; votes[index].voters[msg.sender].votedProposalId = votedProposalId; votes[index].proposals[votedProposalId].voteCount += 1; // Check the winning proposal if (votes[index].maxVoteCount<votes[index].proposals[votedProposalId].voteCount){ votes[index].winningProposalId = votedProposalId; votes[index].maxVoteCount = votes[index].proposals[votedProposalId].voteCount; } emit Voted(index, msg.sender, votedProposalId); } // Some usefull getter function getVoteCount() external view returns (uint){ return votesCount; } // get the vote purpos at the given index function getVoteTips(uint index) external view returns(string memory){ require(votesCount>index, "13");//Given vote index doesn't exist return votes[index].tips; } // Ask if the sender is the vote owner function isOwner(uint index) external view returns(bool){ require(votesCount>index, "13"); return votes[index].owner==msg.sender; } // Ask if the sender has been registered in the vote by the owner function isRegistered(uint index) external view returns(bool){ require(votesCount>index, "13"); return votes[index].voters[msg.sender].isRegistered; } // Get the current status of the vote as an ID (not very human readeable) function getWorkflowStatus(uint index) external view returns (WorkflowStatus) { require(votesCount>index, "13"); return votes[index].statusId; } function getProposalCount(uint index) external view returns(uint){ require(votesCount>index, "13"); return votes[index].proposals.length; } function getProposalDescriptionById(uint index, uint ProposalId) public view returns (string memory){ require(votesCount>index, "13"); require(votes[index].proposals.length>ProposalId, '12'); return votes[index].proposals[ProposalId].description; } // As explaned in the exercise, everyone can check the final details of the winning proposal so i did'n put the onlyRegistered modifier. function getWinningProposalDescription(uint index) external view returns (string memory){ require(votesCount>index, "13"); require(votes[index].statusId==WorkflowStatus.VotesTallied, '15');//Vote not tallied yet return getProposalDescriptionById(index, votes[index].winningProposalId); } function getProposalVoteCountById(uint index, uint ProposalId) external view onlyRegisteredOrOwner(index) returns (uint){ require(votesCount>index, "13"); require(votes[index].proposals.length>ProposalId, '12'); return votes[index].proposals[ProposalId].voteCount; } function getVotedProposalIdByAddress(uint index, address _address) external view returns (int){ require(votesCount>index, "13"); require(votes[index].statusId==WorkflowStatus.VotesTallied || votes[index].statusId==WorkflowStatus.VotingSessionStarted || votes[index].statusId==WorkflowStatus.VotingSessionEnded, 'Vote not started yet'); require(votes[index].voters[_address].hasVoted, '14');//This address has not voted return int(votes[index].voters[_address].votedProposalId); } function hasVoted(uint index, address _address) external view returns (bool){ require(votesCount>index, "13"); return votes[index].voters[_address].hasVoted; } // get front vote informations function getFullPersonalVoteInfo(uint index) external view returns(string memory, uint, bool, int, bool, uint){ require(votesCount>index, "13"); string memory tips = votes[index].tips; uint state = uint(this.getWorkflowStatus(index)); bool registered = votes[index].voters[msg.sender].isRegistered; int votedIndex = -1; uint winningProposalId = 0; if (registered && this.hasVoted(index, msg.sender)){ votedIndex = this.getVotedProposalIdByAddress(index, msg.sender); winningProposalId = votes[index].winningProposalId; } bool owner = _isOwner(index, msg.sender); return (tips, state, registered, votedIndex, owner, winningProposalId); } }
As explaned in the exercise, everyone can check the final details of the winning proposal so i did'n put the onlyRegistered modifier.
function getWinningProposalDescription(uint index) external view returns (string memory){ require(votesCount>index, "13"); return getProposalDescriptionById(index, votes[index].winningProposalId); }
12,942,844
pragma solidity ^0.5.0; library Pairing { struct G1Point { uint X; uint Y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint[2] X; uint[2] Y; } /// @return the generator of G1 function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); } /// @return the generator of G2 function P2() internal pure returns (G2Point memory) { return G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); } /// @return the negation of p, i.e. p.add(p.negate()) should be zero. function negate(G1Point memory p) internal pure returns (G1Point memory) { // The prime q in the base field F_q for G1 uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; if (p.X == 0 && p.Y == 0) return G1Point(0, 0); return G1Point(p.X, q - (p.Y % q)); } /// @return the sum of two points of G1 function pointAdd(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { uint[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success; assembly { success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60) } require(success); } /// @return the product of a point on G1 and a scalar, i.e. /// p == p.mul(1) and p.add(p) == p.mul(2) for all points p. function pointMul(G1Point memory p, uint s) internal view returns (G1Point memory r) { uint[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s; bool success; assembly { success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60) } require (success); } /// @return the result of computing the pairing check /// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 /// For example pairing([P1(), P1().negate()], [P2(), P2()]) should /// return true. function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length); uint elements = p1.length; uint inputSize = elements * 6; uint[] memory input = new uint[](inputSize); for (uint i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint[1] memory out; bool success; assembly { success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } /// Convenience method for a pairing check for three pairs. function pairingProd3( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](3); G2Point[] memory p2 = new G2Point[](3); p1[0] = a1; p1[1] = b1; p1[2] = c1; p2[0] = a2; p2[1] = b2; p2[2] = c2; return pairing(p1, p2); } /// Convenience method for a pairing check for four pairs. function pairingProd4( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2, G1Point memory d1, G2Point memory d2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](4); G2Point[] memory p2 = new G2Point[](4); p1[0] = a1; p1[1] = b1; p1[2] = c1; p1[3] = d1; p2[0] = a2; p2[1] = b2; p2[2] = c2; p2[3] = d2; return pairing(p1, p2); } } library Verifier { using Pairing for Pairing.G1Point; using Pairing for Pairing.G2Point; function scalarField () internal pure returns (uint256) { return 21888242871839275222246405745257275088548364400416034343698204186575808495617; } struct VerifyingKey { Pairing.G1Point alpha; Pairing.G2Point beta; Pairing.G2Point gamma; Pairing.G2Point delta; Pairing.G1Point[] gammaABC; } struct Proof { Pairing.G1Point A; Pairing.G2Point B; Pairing.G1Point C; } struct ProofWithInput { Proof proof; uint256[] input; } function negateY( uint256 Y ) internal pure returns (uint256) { uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; return q - (Y % q); } /* * This implements the Solidity equivalent of the following Python code: from py_ecc.bn128 import * data = # ... arguments to function [in_vk, vk_gammaABC, in_proof, proof_inputs] vk = [int(_, 16) for _ in data[0]] ic = [FQ(int(_, 16)) for _ in data[1]] proof = [int(_, 16) for _ in data[2]] inputs = [int(_, 16) for _ in data[3]] it = iter(ic) ic = [(_, next(it)) for _ in it] vk_alpha = [FQ(_) for _ in vk[:2]] vk_beta = (FQ2(vk[2:4][::-1]), FQ2(vk[4:6][::-1])) vk_gamma = (FQ2(vk[6:8][::-1]), FQ2(vk[8:10][::-1])) vk_delta = (FQ2(vk[10:12][::-1]), FQ2(vk[12:14][::-1])) assert is_on_curve(vk_alpha, b) assert is_on_curve(vk_beta, b2) assert is_on_curve(vk_gamma, b2) assert is_on_curve(vk_delta, b2) proof_A = [FQ(_) for _ in proof[:2]] proof_B = (FQ2(proof[2:4][::-1]), FQ2(proof[4:-2][::-1])) proof_C = [FQ(_) for _ in proof[-2:]] assert is_on_curve(proof_A, b) assert is_on_curve(proof_B, b2) assert is_on_curve(proof_C, b) vk_x = ic[0] for i, s in enumerate(inputs): vk_x = add(vk_x, multiply(ic[i + 1], s)) check_1 = pairing(proof_B, proof_A) check_2 = pairing(vk_beta, neg(vk_alpha)) check_3 = pairing(vk_gamma, neg(vk_x)) check_4 = pairing(vk_delta, neg(proof_C)) ok = check_1 * check_2 * check_3 * check_4 assert ok == FQ12.one() */ function verify (uint256[14] memory in_vk, uint256[] memory vk_gammaABC, uint256[8] memory in_proof, uint256[] memory proof_inputs) internal view returns (bool) { require( ((vk_gammaABC.length / 2) - 1) == proof_inputs.length ); // Compute the linear combination vk_x uint256[3] memory mul_input; uint256[4] memory add_input; bool success; uint m = 2; // First two fields are used as the sum add_input[0] = vk_gammaABC[0]; add_input[1] = vk_gammaABC[1]; // Performs a sum of gammaABC[0] + sum[ gammaABC[i+1]^proof_inputs[i] ] for (uint i = 0; i < proof_inputs.length; i++) { mul_input[0] = vk_gammaABC[m++]; mul_input[1] = vk_gammaABC[m++]; mul_input[2] = proof_inputs[i]; assembly { // ECMUL, output to last 2 elements of `add_input` success := staticcall(sub(gas, 2000), 7, mul_input, 0x80, add(add_input, 0x40), 0x60) } require(success); assembly { // ECADD success := staticcall(sub(gas, 2000), 6, add_input, 0xc0, add_input, 0x60) } require(success); } uint[24] memory input = [ // (proof.A, proof.B) in_proof[0], in_proof[1], // proof.A (G1) in_proof[2], in_proof[3], in_proof[4], in_proof[5], // proof.B (G2) // (-vk.alpha, vk.beta) in_vk[0], negateY(in_vk[1]), // -vk.alpha (G1) in_vk[2], in_vk[3], in_vk[4], in_vk[5], // vk.beta (G2) // (-vk_x, vk.gamma) add_input[0], negateY(add_input[1]), // -vk_x (G1) in_vk[6], in_vk[7], in_vk[8], in_vk[9], // vk.gamma (G2) // (-proof.C, vk.delta) in_proof[6], negateY(in_proof[7]), // -proof.C (G1) in_vk[10], in_vk[11], in_vk[12], in_vk[13] // vk.delta (G2) ]; uint[1] memory out; assembly { success := staticcall(sub(gas, 2000), 8, input, 768, out, 0x20) } require(success); return out[0] != 0; } function verify(VerifyingKey memory vk, ProofWithInput memory pwi) internal view returns (bool) { return verify(vk, pwi.proof, pwi.input); } function verify(VerifyingKey memory vk, Proof memory proof, uint256[] memory input) internal view returns (bool) { require(input.length + 1 == vk.gammaABC.length); // Compute the linear combination vk_x Pairing.G1Point memory vk_x = vk.gammaABC[0]; for (uint i = 0; i < input.length; i++) vk_x = Pairing.pointAdd(vk_x, Pairing.pointMul(vk.gammaABC[i + 1], input[i])); // Verify proof return Pairing.pairingProd4( proof.A, proof.B, vk_x.negate(), vk.gamma, proof.C.negate(), vk.delta, vk.alpha.negate(), vk.beta); } } library MiMC { function getScalarField () internal pure returns (uint256) { return 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; } /** * MiMC-p/p with exponent of 7 * * Recommended at least 46 rounds, for a polynomial degree of 2^126 */ function MiMCpe7( uint256 in_x, uint256 in_k, uint256 in_seed, uint256 round_count ) internal pure returns(uint256 out_x) { assembly { if lt(round_count, 1) { revert(0, 0) } // Initialise round constants, k will be hashed let c := mload(0x40) mstore(0x40, add(c, 32)) mstore(c, in_seed) let localQ := 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 let t let a // Further n-2 subsequent rounds include a round constant for { let i := round_count } gt(i, 0) { i := sub(i, 1) } { // c = H(c) mstore(c, keccak256(c, 32)) // x = pow(x + c_i, 7, p) + k t := addmod(addmod(in_x, mload(c), localQ), in_k, localQ) // t = x + c_i + k a := mulmod(t, t, localQ) // t^2 in_x := mulmod(mulmod(a, mulmod(a, a, localQ), localQ), t, localQ) // t^7 } // Result adds key again as blinding factor out_x := addmod(in_x, in_k, localQ) } } function MiMCpe7_mp( uint256[] memory in_x, uint256 in_k, uint256 in_seed, uint256 round_count ) internal pure returns (uint256) { uint256 r = in_k; uint256 localQ = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; for( uint256 i = 0; i < in_x.length; i++ ) { r = (r + in_x[i] + MiMCpe7(in_x[i], r, in_seed, round_count)) % localQ; } // uint256 x0 = in_x[0]; // uint256 x1 = in_x[1]; // uint256 m0 = MiMCpe7(x0, r, in_seed, round_count); // assembly { // r := addmod(addmod(r, x0, localQ), m0, localQ) // } // uint256 m1 = MiMCpe7(x1, r, in_seed, round_count); // assembly { // r := addmod(addmod(r, x1, localQ), m1, localQ) // } return r; } function Hash( uint256[] memory in_msgs, uint256 in_key ) internal pure returns (uint256) { return MiMCpe7_mp(in_msgs, in_key, uint256(keccak256("mimc")), 91); } function Hash( uint256[] memory in_msgs ) internal pure returns (uint256) { return Hash(in_msgs, 0); } } library MerkleTree { // ceil(log2(1<<15)) uint constant internal TREE_DEPTH = 15; // 1<<15 leaves uint constant internal MAX_LEAF_COUNT = 32768; struct Data { uint cur; uint256[32768][16] nodes; // first column = leaves, second column = leaves' parents, etc } function treeDepth() internal pure returns (uint256) { return TREE_DEPTH; } function fillLevelIVs (uint256[15] memory IVs) internal pure { IVs[0] = 149674538925118052205057075966660054952481571156186698930522557832224430770; IVs[1] = 9670701465464311903249220692483401938888498641874948577387207195814981706974; IVs[2] = 18318710344500308168304415114839554107298291987930233567781901093928276468271; IVs[3] = 6597209388525824933845812104623007130464197923269180086306970975123437805179; IVs[4] = 21720956803147356712695575768577036859892220417043839172295094119877855004262; IVs[5] = 10330261616520855230513677034606076056972336573153777401182178891807369896722; IVs[6] = 17466547730316258748333298168566143799241073466140136663575045164199607937939; IVs[7] = 18881017304615283094648494495339883533502299318365959655029893746755475886610; IVs[8] = 21580915712563378725413940003372103925756594604076607277692074507345076595494; IVs[9] = 12316305934357579015754723412431647910012873427291630993042374701002287130550; IVs[10] = 18905410889238873726515380969411495891004493295170115920825550288019118582494; IVs[11] = 12819107342879320352602391015489840916114959026915005817918724958237245903353; IVs[12] = 8245796392944118634696709403074300923517437202166861682117022548371601758802; IVs[13] = 16953062784314687781686527153155644849196472783922227794465158787843281909585; IVs[14] = 19346880451250915556764413197424554385509847473349107460608536657852472800734; } function hashImpl (uint256 left, uint256 right, uint256 IV) internal pure returns (uint256) { uint256[] memory x = new uint256[](2); x[0] = left; x[1] = right; return MiMC.Hash(x, IV); } function insert(Data storage self, uint256 leaf) internal returns (uint256 new_root, uint256 offset) { require(leaf != 0); uint256[15] memory IVs; fillLevelIVs(IVs); offset = self.cur; require(offset != MAX_LEAF_COUNT - 1); self.nodes[0][offset] = leaf; new_root = updateTree(self, IVs); self.cur = offset + 1; } /** * Returns calculated merkle root */ function verifyPath(uint256 leaf, uint256[15] memory in_path, bool[15] memory address_bits) internal pure returns (uint256 merkleRoot) { uint256[15] memory IVs; fillLevelIVs(IVs); merkleRoot = leaf; for (uint depth = 0; depth < TREE_DEPTH; depth++) { if (address_bits[depth]) { merkleRoot = hashImpl(in_path[depth], merkleRoot, IVs[depth]); } else { merkleRoot = hashImpl(merkleRoot, in_path[depth], IVs[depth]); } } } function verifyPath(Data storage self, uint256 leaf, uint256[15] memory in_path, bool[15] memory address_bits) internal view returns (bool) { return verifyPath(leaf, in_path, address_bits) == getRoot(self); } function getLeaf(Data storage self, uint depth, uint offset) internal view returns (uint256) { return getUniqueLeaf(depth, offset, self.nodes[depth][offset]); } function getMerkleProof(Data storage self, uint index) internal view returns (uint256[15] memory proof_path) { for (uint depth = 0; depth < TREE_DEPTH; depth++) { if (index % 2 == 0) { proof_path[depth] = getLeaf(self, depth, index + 1); } else { proof_path[depth] = getLeaf(self, depth, index - 1); } index = uint(index / 2); } } function getUniqueLeaf(uint256 depth, uint256 offset, uint256 leaf) internal pure returns (uint256) { if (leaf == 0x0) { leaf = uint256( sha256( abi.encodePacked( uint16(depth), uint240(offset)))) % MiMC.getScalarField(); } return leaf; } function updateTree(Data storage self, uint256[15] memory IVs) internal returns(uint256 root) { uint currentIndex = self.cur; uint256 leaf1; uint256 leaf2; for (uint depth = 0; depth < TREE_DEPTH; depth++) { if (currentIndex%2 == 0) { leaf1 = self.nodes[depth][currentIndex]; leaf2 = getUniqueLeaf(depth, currentIndex + 1, self.nodes[depth][currentIndex + 1]); } else { leaf1 = getUniqueLeaf(depth, currentIndex - 1, self.nodes[depth][currentIndex - 1]); leaf2 = self.nodes[depth][currentIndex]; } uint nextIndex = uint(currentIndex/2); self.nodes[depth+1][nextIndex] = hashImpl(leaf1, leaf2, IVs[depth]); currentIndex = nextIndex; } return self.nodes[TREE_DEPTH][0]; } function getRoot (Data storage self) internal view returns (uint256) { return self.nodes[TREE_DEPTH][0]; } function getNextLeafIndex (Data storage self) internal view returns (uint256) { return self.cur; } } contract Mixer { using MerkleTree for MerkleTree.Data; uint constant public AMOUNT = 1 ether; uint256[14] vk; uint256[] gammaABC; mapping (uint256 => bool) public nullifiers; mapping (address => uint256[]) public pendingDeposits; MerkleTree.Data internal tree; event CommitmentAdded(address indexed _fundingWallet, uint256 _leaf); event LeafAdded(uint256 _leaf, uint256 _leafIndex); constructor(uint256[14] memory in_vk, uint256[] memory in_gammaABC) public { vk = in_vk; gammaABC = in_gammaABC; } function getRoot() public view returns (uint256) { return tree.getRoot(); } /** * Save a commitment (leaf) that needs to be funded later on */ function commit(uint256 leaf, address fundingWallet) public payable { require(leaf > 0, "null leaf"); pendingDeposits[fundingWallet].push(leaf); emit CommitmentAdded(fundingWallet, leaf); if (msg.value > 0) fundCommitment(); } function fundCommitment() private { require(msg.value == AMOUNT, "wrong value"); uint256[] storage leaves = pendingDeposits[msg.sender]; require(leaves.length > 0, "commitment must be sent first"); uint256 leaf = leaves[leaves.length - 1]; leaves.length--; (, uint256 leafIndex) = tree.insert(leaf); emit LeafAdded(leaf, leafIndex); } /* * Used by the funding wallet to fund a previously saved commitment */ function () external payable { fundCommitment(); } function makeLeafHash(uint256 nullifier_secret, address wallet_address) external pure returns (uint256) { bytes32 digest = sha256(abi.encodePacked(nullifier_secret, uint256(wallet_address))); uint256 mask = uint256(-1) >> 4; // clear the first 4 bits to make sure we stay within the prime field return uint256(digest) & mask; } function makeNullifierHash(uint256 nullifier_secret) external pure returns (uint256) { uint256[] memory vals = new uint256[](2); vals[0] = nullifier_secret; vals[1] = nullifier_secret; return MiMC.Hash(vals, 0); } function getMerklePath(uint256 leafIndex) external view returns (uint256[15] memory out_path) { out_path = tree.getMerkleProof(leafIndex); } function isSpent(uint256 nullifier) public view returns (bool) { return nullifiers[nullifier]; } function verifyProof(uint256 in_root, address in_wallet_address, uint256 in_nullifier, uint256[8] memory proof) public view returns (bool) { uint256[] memory snark_input = new uint256[](3); snark_input[0] = in_root; snark_input[1] = uint256(in_wallet_address); snark_input[2] = in_nullifier; return Verifier.verify(vk, gammaABC, proof, snark_input); } function withdraw( address payable in_withdraw_address, uint256 in_nullifier, uint256[8] memory proof ) public { uint startGas = gasleft(); require(!nullifiers[in_nullifier], "Nullifier used"); require(verifyProof(getRoot(), in_withdraw_address, in_nullifier, proof), "Proof verification failed"); nullifiers[in_nullifier] = true; uint gasUsed = startGas - gasleft() + 82775; uint relayerRefund = gasUsed * tx.gasprice; if(relayerRefund > AMOUNT/20) relayerRefund = AMOUNT/20; in_withdraw_address.transfer(AMOUNT - relayerRefund); // leaf withdrawal msg.sender.transfer(relayerRefund); // relayer refund } function treeDepth() external pure returns (uint256) { return MerkleTree.treeDepth(); } function getNextLeafIndex() external view returns (uint256) { return tree.getNextLeafIndex(); } }
/ Compute the linear combination vk_x First two fields are used as the sum Performs a sum of gammaABC[0] + sum[ gammaABC[i+1]^proof_inputs[i] ] ECMUL, output to last 2 elements of `add_input` ECADD
data = # ... arguments to function [in_vk, vk_gammaABC, in_proof, proof_inputs] vk = [int(_, 16) for _ in data[0]] ic = [FQ(int(_, 16)) for _ in data[1]] proof = [int(_, 16) for _ in data[2]] inputs = [int(_, 16) for _ in data[3]] it = iter(ic) ic = [(_, next(it)) for _ in it] vk_alpha = [FQ(_) for _ in vk[:2]] vk_beta = (FQ2(vk[2:4][::-1]), FQ2(vk[4:6][::-1])) vk_gamma = (FQ2(vk[6:8][::-1]), FQ2(vk[8:10][::-1])) vk_delta = (FQ2(vk[10:12][::-1]), FQ2(vk[12:14][::-1])) assert is_on_curve(vk_alpha, b) assert is_on_curve(vk_beta, b2) assert is_on_curve(vk_gamma, b2) assert is_on_curve(vk_delta, b2) proof_A = [FQ(_) for _ in proof[:2]] proof_B = (FQ2(proof[2:4][::-1]), FQ2(proof[4:-2][::-1])) proof_C = [FQ(_) for _ in proof[-2:]] assert is_on_curve(proof_A, b) assert is_on_curve(proof_B, b2) assert is_on_curve(proof_C, b) vk_x = ic[0] for i, s in enumerate(inputs): vk_x = add(vk_x, multiply(ic[i + 1], s)) check_1 = pairing(proof_B, proof_A) check_2 = pairing(vk_beta, neg(vk_alpha)) check_3 = pairing(vk_gamma, neg(vk_x)) check_4 = pairing(vk_delta, neg(proof_C)) ok = check_1 * check_2 * check_3 * check_4 assert ok == FQ12.one() function verify (uint256[14] memory in_vk, uint256[] memory vk_gammaABC, uint256[8] memory in_proof, uint256[] memory proof_inputs) internal view returns (bool) { require( ((vk_gammaABC.length / 2) - 1) == proof_inputs.length ); uint256[3] memory mul_input; uint256[4] memory add_input; bool success; uint m = 2; add_input[0] = vk_gammaABC[0]; add_input[1] = vk_gammaABC[1]; for (uint i = 0; i < proof_inputs.length; i++) { mul_input[0] = vk_gammaABC[m++]; mul_input[1] = vk_gammaABC[m++]; mul_input[2] = proof_inputs[i]; assembly { success := staticcall(sub(gas, 2000), 7, mul_input, 0x80, add(add_input, 0x40), 0x60) } require(success); assembly { success := staticcall(sub(gas, 2000), 6, add_input, 0xc0, add_input, 0x60) } require(success); } uint[24] memory input = [ uint[1] memory out; assembly { success := staticcall(sub(gas, 2000), 8, input, 768, out, 0x20) } require(success); return out[0] != 0; }
7,233,475
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./openzeppelin/ERC20.sol"; import "./openzeppelin/AccessControlEnumerable.sol"; import "./BeezToken.sol"; contract WonToken is AccessControlEnumerable, ERC20{ constructor() ERC20('WON', 'WON') { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } struct chargeStruct{ uint256 lastChargeDate; //마지막 인센티브 충전 날짜 체크 uint128 wonOfMonth; //이번달 충전 금액 //maxWonCharge - wonOfMonth[address] : 이번달 충전가능금액(charge.vue에 출력) //사용자소상공인 사용 uint128 incentiveOfMonth; //이번달 인센티브 금액 //maxIncentive - incentiveOfMonth[address] : 이번달 혜택가능금액(charge.vue에 출력) //사용자만 사용, 소상공인은 쓰지 않음 } mapping (address => chargeStruct) chargeStructCheck; //주소 넣어서 인센티브 구조체 가져오는 매핑 mapping (address => uint128) incentive; // DB에 저장할 인센티브차지 매핑 uint128 incentiveRate; //인센티브 비율 uint256 month = 1627743600; //매달 초기화(이달 1일을 나타냄) uint8 decimals = 10**0; //decimals 10**18 X / 10**0 = etherscan, remix 보기 편함 uint128 maxIncentive = 500000; //한달 혜택가능금액 uint128 maxWonCharge = 2000000; //한달 충전가능금액 uint128 minWonCharge = 10000; //충전은 10000원 이상 bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); //충전결과 로그 event chargeResult(address indexed to, uint128 chargeAmount , uint128 chargeInc); //출금결과 로그 event withDrawResult(address indexed to, uint128 withDrawAmount); /******************************************************************************************************************/ /***사용자, 소상공인 MAIN화면 매달 초기화 함수(사용자 : 이달의 충전금액, 이달의 인센티브 & 소상공인 : 현금매출)****/ //매달 초기화 함수 function updateMonth(address _address, uint256 _date) private { //금액 충전시 마지막으로 인센티브 충전된 날짜가 지난달인 경우 (block.timestamp >= month && =>이건 빼야됨) if(chargeStructCheck[_address].lastChargeDate < month){ chargeStructCheck[_address].wonOfMonth = 0; //인센티브 밸런스 초기화(여기서 이번에 충전된 ) chargeStructCheck[_address].incentiveOfMonth = 0; } //(나중에 다시 block.timestamp으로 수정) chargeStructCheck[_address].lastChargeDate = _date; //최근 인센티브 충전된 날짜 현재시간으로 업데이트 } //매달 변경될때, aws람다를 사용해 백앤드에 요청을 보낸다. 요청받은 백앤드는 현재 시간(UNIX시간)을 setMonth에 입력 function setMonth(uint256 _month) external { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); month = _month; } function getMonth() external view returns (uint256) { return month; } /******************************************************************************************************************/ /*********사용자 충전 / 소상공인 환전&출금에 사용되는 생성(mint), 소멸(burn) /사용자, 소상공인 결재 함수***********/ //충전 function charge(address _to, uint256 _amount) internal virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(_to, _amount*decimals); } //인센티브 충전 function incentiveCharge(address _to, uint128 _amount) internal virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); incentiveRate = _amount/10; _mint(_to, (_amount + incentiveRate)*decimals); chargeStructCheck[_to].incentiveOfMonth += incentiveRate; } //충전 + 인센티브 충전 function chargeCheck(address _to, uint128 _amount) external { //한달 최대 충전량 require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); updateMonth(_to, block.timestamp); //require 전에 해줘야됨. 전달+지금충전하려는 금액이 2백이 넘으면 실행 불가. require(_amount >= minWonCharge); // //최소충전금액 10000원을 넘어야 충전가능 require(chargeStructCheck[_to].wonOfMonth + _amount <= maxWonCharge); //최대충전금액 2000000원을 넘지않아야함 chargeStructCheck[_to].wonOfMonth += _amount; //이번달 충전금액(현재 충전할 금액을 더한)이 최대인센티브(50만원) 보다 작거나 같으면 인센티브 충전 if(chargeStructCheck[_to].wonOfMonth <= maxIncentive){ incentiveCharge(_to, _amount); incentive[_to] = _amount/10; emit chargeResult(_to, _amount, _amount/10); }else{ //이번달 충전 금액(현재 충전금액을 뺀)이 최대 인센티브보다 적다 if(chargeStructCheck[_to].wonOfMonth - _amount < maxIncentive){ uint128 inc = maxIncentive - (chargeStructCheck[_to].wonOfMonth - _amount); charge(_to, chargeStructCheck[_to].wonOfMonth - maxIncentive); incentiveCharge(_to, inc); incentive[_to] = inc/10; emit chargeResult(_to, _amount, inc/10); } else{ charge(_to, _amount); incentive[_to] = 0; emit chargeResult(_to, _amount, 0); } } } //소상공인 환전 함수 function exchangeCharge(address _to, uint128 _amount) external virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(_to, _amount*decimals); } //소상공인 출금 함수 function withDraw(address _to, uint128 _amount) external { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _burn(_to, _amount*decimals); chargeStructCheck[_to].incentiveOfMonth += _amount; emit withDrawResult(_to, _amount); } //원화 토큰 결제 function payment(address _sender, address _recipient, uint128 _amount, uint256 _date) external virtual returns (bool){ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); updateMonth(_recipient, _date); //_date는 나중에 뺄꺼임. 이번달 첫 결재할 경우, 소상공인 incentiveCheck[_recipient].wonOfMonth 0으로 만들기 위해 // _transfer(_sender, _recipient, _amount*decimals); //won 결제 chargeStructCheck[_recipient].wonOfMonth += _amount; //소상공인 (이번달)현금매출 증가 return true; } /******************************************************************************************************************/ /*************************사용자, 소상공인 MAIN화면에 출력되는 원화토큰 view 함수*********************************/ //이달의 충전금액 ////인센티브 정확히 카운팅하는 함수 //결제히스토리용 함수 function balanceWonOfMon(address _to) external view returns (uint128){ if(chargeStructCheck[_to].lastChargeDate < month){ return 0; } else{ return chargeStructCheck[_to].wonOfMonth; } } //이번달 인센티브 확인 function balanceIncOfMon(address _to) external view returns (uint128) { if(chargeStructCheck[_to].lastChargeDate < month){ return 0; } else{ return chargeStructCheck[_to].incentiveOfMonth; //*(-10**18) } } //현재 보유 원화 function balance(address _account) external view virtual returns(uint256) { return balanceOf(_account); //* (10 ** 18) } /******************************************************************************************************************/ /***************************************************권한**********************************************************/ function addMinter(address _address) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to addMinter"); _setupRole(MINTER_ROLE, _address); } }
/권한/
function addMinter(address _address) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to addMinter"); _setupRole(MINTER_ROLE, _address); }
2,478,678
./partial_match/4/0x2F674500a367583D6Aaef312478a7cC1941a1977/sources/FECORE.sol
Removes a value from a set. O(1). Returns true if the value was removed from the set, that is if it was present./ We read and store the value's index to prevent multiple reads from the same storage slot 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}. 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. Move the last value to the index where the value to delete is Update the index for the moved value Delete the slot where the moved value was stored Delete the index for the deleted slot
function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._values.pop(); delete set._indexes[value]; return true; return false; } }
8,664,314
./full_match/8453/0xE4AD80eD0c7d12A8B687c6C987d07f1D486fEd85/sources/src/token/ERC721/ERC721AB.sol
Mint `_quantity` tokens to `_to` address based on the current `_phaseId` if `_signature` is valid _to token recipient address (must be whitelisted) _phaseId current minting phase (must be started) _quantity quantity of tokens requested (must be less than max mint per phase) _signature signature to verify allowlist status/ Check that the requested minting phase has started Get requested phase details Check that there are enough tokens available for sale Check if the current phase is private Check that the user is included in the allowlist
function mint(address _to, uint256 _phaseId, uint256 _quantity, bytes calldata _signature) external payable { if (!_isPhaseActive(_phaseId)) revert ABErrors.PHASE_NOT_ACTIVE(); ABDataTypes.Phase memory phase = phases[_phaseId]; if (_totalMinted() + _quantity > maxSupply) { revert ABErrors.NOT_ENOUGH_TOKEN_AVAILABLE(); } if (!phase.isPublic) { if (!abVerifier.verifySignature721(_to, address(this), _phaseId, _signature)) { revert ABErrors.NOT_ELIGIBLE(); } } }
11,535,287
pragma solidity 0.5.10; contract Context { constructor () internal { } function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; return msg.data; } } interface IERC20 { function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(a, b, "SafeMath: subtraction overflow"); } function SUB97(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 MUL111(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 DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV358(a, b, "SafeMath: division by zero"); } function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD464(a, b, "SafeMath: modulo by zero"); } function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(_MSGSENDER793(), recipient, amount); return true; } function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, amount); return true; } function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(sender, recipient, amount); _APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue)); return true; } function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER927(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].SUB97(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD803(amount); emit TRANSFER432(sender, recipient, amount); } function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD803(amount); _balances[account] = _balances[account].ADD803(amount); emit TRANSFER432(address(0), account, amount); } function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB97(amount); emit TRANSFER432(account, address(0), amount); } function _APPROVE171(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 APPROVAL431(owner, spender, amount); } function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN826(account, amount); _APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance")); } } library BytesLib { function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory tempBytes; assembly { tempBytes := mload(0x40) let length := mload(_preBytes) mstore(tempBytes, length) let mc := add(tempBytes, 0x20) let end := add(mc, length) for { let cc := add(_preBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) mc := end end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) )) } return tempBytes; } function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) switch add(lt(slength, 32), lt(newlength, 32)) case 2 { sstore( _preBytes_slot, add( fslot, add( mul( div( mload(add(_postBytes, 0x20)), exp(0x100, sub(32, mlength)) ), exp(0x100, sub(32, newlength)) ), mul(mlength, 2) ) ) ) } case 1 { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + _length), "Slice out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { 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) mstore(0x40, and(add(mc, 31), not(31))) } default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 20), "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32), "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let length := mload(_preBytes) switch eq(length, mload(_postBytes)) case 1 { let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { if iszero(eq(mload(mc), mload(cc))) { success := 0 cb := 0 } } } default { success := 0 } } return success; } function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) switch eq(slength, mlength) case 1 { if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { success := 0 } } default { let cb := 1 mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { success := 0 cb := 0 } } } } } default { success := 0 } } return success; } function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING bytes memory tempEmptyStringTest = bytes(_source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } } library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING if (uint8(_flag[0]) == 0xff) { return 8; } if (uint8(_flag[0]) == 0xfe) { return 4; } if (uint8(_flag[0]) == 0xfd) { return 2; } return 0; } function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _start = _b.length.SUB97(_num); return _b.SLICE479(_start, _num); } function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571(); } function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); _offset = _offset + _len; } _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); return _vin.SLICE479(_offset, _len); } function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00"); } function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input); bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_beSequence)); } function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen); } function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING bytes memory _varIntTag = _input.SLICE479(36, 1); uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag); uint256 _len; if (_varIntDataLen == 0) { _len = uint8(_varIntTag[0]); } else { _len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen))); } return (_varIntDataLen, _len); } function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(37, 4); } function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input); bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_inputeSequence)); } function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 36); } function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 32).TOBYTES32571(); } function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input)); bytes memory _beId = REVERSEENDIANNESS18(_leId); return _beId.TOBYTES32571(); } function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(32, 4); } function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leIndex = EXTRACTTXINDEXLE408(_input); bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex); return uint32(BYTESTOUINT790(_beIndex)); } function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _len = uint8(_output.SLICE479(8, 1)[0]); require(_len < 0xfd, "Multi-byte VarInts not supported"); return _len + 8 + 1; } function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); _offset = _offset + _len; } _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); return _vout.SLICE479(_offset, _len); } function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(8, 1); } function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(0, 8); } function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING bytes memory _leValue = EXTRACTVALUELE862(_output); bytes memory _beValue = REVERSEENDIANNESS18(_leValue); return uint64(BYTESTOUINT790(_beValue)); } function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.SLICE479(10, 1); return _output.SLICE479(11, BYTESTOUINT790(_dataLen)); } function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (uint8(_output.SLICE479(9, 1)[0]) == 0) { uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2; if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) { return hex""; } return _output.SLICE479(11, _len); } else { bytes32 _tag = keccak256(_output.SLICE479(8, 3)); if (_tag == keccak256(hex"1976a9")) { if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 || keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) { return hex""; } return _output.SLICE479(12, 20); } else if (_tag == keccak256(hex"17a914")) { if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) { return hex""; } return _output.SLICE479(11, 20); } } return hex""; } function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]); if (_nIns >= 0xfd || _nIns == 0) { return false; } for (uint8 i = 0; i < _nIns; i++) { _offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset)); if (_offset > _vin.length) { return false; } } return _offset == _vin.length; } function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]); if (_nOuts >= 0xfd || _nOuts == 0) { return false; } for (uint8 i = 0; i < _nOuts; i++) { _offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset)); if (_offset > _vout.length) { return false; } } return _offset == _vout.length; } function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(36, 32); } function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header)); } function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING bytes memory _m = _header.SLICE479(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING return diff1_target719.DIV358(_target); } function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(4, 32); } function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header)); } function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(68, 4); } function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header)))); } function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header)); } function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return HASH256986(abi.encodePacked(_a, _b)); } function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING if (_proof.length % 32 != 0) { return false; } if (_proof.length == 32) { return true; } if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571(); bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571(); for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current)); } else { _current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } function RETARGETALGORITHM78( //inject NONSTANDARD NAMING uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp); if (_elapsedTime < retarget_period820.DIV358(4)) { _elapsedTime = retarget_period820.DIV358(4); } if (_elapsedTime > retarget_period820.MUL111(4)) { _elapsedTime = retarget_period820.MUL111(4); } uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime); return _adjusted.DIV358(retarget_period820).MUL111(65536); } } interface FundsInterface { function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING } interface SalesInterface { function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING } interface CollateralInterface { function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING } contract DSMath { function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x + y) >= x); } function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x - y) <= x); } function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require(y == 0 || (z = x * y) / y == x); } function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING require(b > 0); c = a / b; } function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), col735 / 2) / col735; } function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), wad510 / 2) / wad510; } function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), ray271 / 2) / ray271; } function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, col735), y / 2) / y; } function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, wad510), y / 2) / y; } function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, ray271), y / 2) / y; } function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = n % 2 != 0 ? x : ray271; for (n /= 2; n != 0; n /= 2) { x = RMUL965(x, x); if (n % 2 != 0) { z = RMUL965(z, x); } } } } contract Medianizer { function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING function READ913() external returns (bytes32); //inject NONSTANDARD NAMING function POKE561() external; //inject NONSTANDARD NAMING function POKE561(bytes32) external; //inject NONSTANDARD NAMING function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING } contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; mapping (bytes32 => SecretHashes) public secretHashes; mapping (bytes32 => Bools) public bools; mapping (bytes32 => bytes32) public fundIndex; mapping (bytes32 => uint256) public repayments; mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; ERC20 public token; uint256 public decimals; address deployer; struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].borrower; } function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].lender; } function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].arbiter; } function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].createdAt, approve_exp_threshold840); } function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, accept_exp_threshold947); } function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443); } function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699); } function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].principal; } function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].interest; } function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].fee; } function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].penalty; } function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return col.COLLATERAL382(loan); } function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.REFUNDABLECOLLATERAL879(loan); } function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.SEIZABLECOLLATERAL368(loan); } function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYREFUNDABLECOLLATERAL760(loan); } function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYSEIZABLECOLLATERAL228(loan); } function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return repayments[loan]; } function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].liquidationRatio; } function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(PRINCIPAL566(loan), INTEREST523(loan)); } function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDTOLENDER7(loan), FEE426(loan)); } function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan)); } function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return SUB97(OWEDFORLOAN262(loan), REPAID307(loan)); } function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].funded; } function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].approved; } function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].withdrawn; } function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].sale; } function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].paid; } function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].off; } function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return MUL111(x, (10 ** SUB97(18, decimals))); } function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return DIV358(x, (10 ** SUB97(18, decimals))); } function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING return borrowerLoans[borrower_].length; } function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING return lenderLoans[lender_].length; } function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735)); } function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return CMUL87(price, COLLATERAL382(loan)); } function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan)); } function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317); } function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan); } constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed"); } function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } function CREATE943( //inject NONSTANDARD NAMING uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = ADD803(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan); col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit CREATE22(loan); } function SETSECRETHASHES742( //inject NONSTANDARD NAMING bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens"); emit FUNDLOAN50(loan); } function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit APPROVE490(loan); } function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);} emit WITHDRAW160(loan, secretA1); } function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.repay: Loan cannot be inactive"); require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = ADD803(amount, repayments[loan]); if (REPAID307(loan) == OWEDFORLOAN262(loan)) { bools[loan].paid = true; if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} } emit REPAY404(loan, amount); } function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.refund: Loan cannot be inactive"); require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens"); emit REFUND289(loan); } function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING ACCEPT922(loan, secret); emit CANCEL833(loan, secret); } function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); CLOSE691(loan); emit CANCEL833(loan, bytes32(0)); } function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; CLOSE691(loan); emit ACCEPT489(loan, secret); } function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING bools[loan].off = true; loans[loan].closedTimestamp = now; if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], loans[loan].principal); } } else { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan)); } require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); if (sales.NEXT199(loan) == 0) { if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } } else { require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached"); require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.NEXT199(loan); sale_ = sales.CREATE943( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} emit LIQUIDATE130(loan, secretHash, pubKeyHash); } } interface CTokenInterface { function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface CERC20Interface { function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING } interface ERC20Interface { function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface TrollerInterface { function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING } contract Helpers is DSMath { address public comptroller; function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING return comptroller; } function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117()); address[] memory markets = troller.GETASSETSIN764(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.ENTERMARKETS395(toEnter); } } function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING ERC20Interface erc20Contract = ERC20Interface(erc20); uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.APPROVE357(to, 2**255); } } } contract ALCompound is Helpers { function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING ENTERMARKET780(cErc20); ERC20Interface token = ERC20Interface(erc20); uint toDeposit = token.BALANCEOF227(address(this)); if (toDeposit > tokenAmt) { toDeposit = tokenAmt; } CERC20Interface cToken = CERC20Interface(cErc20); SETAPPROVAL391(erc20, toDeposit, cErc20); assert(cToken.MINT386(toDeposit) == 0); } function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); SETAPPROVAL391(cErc20, 10**50, cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666()); if (tokenToReturn > tokenAmt) { tokenToReturn = tokenAmt; } require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong"); } function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); if (toBurn > cTokenAmt) { toBurn = cTokenAmt; } SETAPPROVAL391(cErc20, toBurn, cErc20); require(cToken.REDEEM46(toBurn) == 0, "something went wrong"); } } contract Funds is DSMath, ALCompound { Loans loans; uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (address => bytes32[]) public secretHashes; mapping (address => uint256) public secretHashIndex; mapping (address => bytes) public pubKeys; mapping (bytes32 => Fund) public funds; mapping (address => bytes32) public fundOwner; mapping (bytes32 => Bools) public bools; uint256 public fundIndex; uint256 public lastGlobalInterestUpdated; uint256 public tokenMarketLiquidity; uint256 public cTokenMarketLiquidity; uint256 public marketLiquidity; uint256 public totalBorrow; uint256 public globalInterestRateNumerator; uint256 public lastUtilizationRatio; uint256 public globalInterestRate; uint256 public maxUtilizationDelta; uint256 public utilizationInterestDivisor; uint256 public maxInterestRateNumerator; uint256 public minInterestRateNumerator; uint256 public interestUpdateDelay; uint256 public defaultArbiterFee; ERC20 public token; uint256 public decimals; CTokenInterface public cToken; bool compoundSet; address deployer; struct Fund { address lender; uint256 minLoanAmt; uint256 maxLoanAmt; uint256 minLoanDur; uint256 maxLoanDur; uint256 fundExpiry; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; address arbiter; uint256 balance; uint256 cBalance; } struct Bools { bool custom; bool compoundEnabled; } event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING constructor( ERC20 token_, uint256 decimals_ ) public { require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero"); require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero"); deployer = msg.sender; token = token_; decimals = decimals_; utilizationInterestDivisor = 10531702972595856680093239305; maxUtilizationDelta = 95310179948351216961192521; globalInterestRateNumerator = 95310179948351216961192521; maxInterestRateNumerator = 182321557320989604265864303; minInterestRateNumerator = 24692612600038629323181834; interestUpdateDelay = 86400; defaultArbiterFee = 1000000000236936036262880196; globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); } function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this"); require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set"); require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero"); loans = loans_; require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved"); } function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending"); require(!compoundSet, "Funds.setCompound: Compound address has already been set"); require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero"); require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero"); cToken = cToken_; comptroller = comptroller_; compoundSet = true; } function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this"); require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero"); utilizationInterestDivisor = utilizationInterestDivisor_; } function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this"); require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero"); maxUtilizationDelta = maxUtilizationDelta_; } function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this"); require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero"); globalInterestRateNumerator = globalInterestRateNumerator_; } function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this"); require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero"); globalInterestRate = globalInterestRate_; } function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this"); require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero"); maxInterestRateNumerator = maxInterestRateNumerator_; } function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this"); require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero"); minInterestRateNumerator = minInterestRateNumerator_; } function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this"); require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero"); interestUpdateDelay = interestUpdateDelay_; } function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this"); require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%"); defaultArbiterFee = defaultArbiterFee_; } function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].lender; } function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanAmt;} else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));} } function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].maxLoanAmt;} else {return default_max_loan_amt507;} } function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanDur;} else {return default_min_loan_dur981;} } function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].maxLoanDur; } function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].fundExpiry; } function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].interest;} else {return globalInterestRate;} } function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].penalty;} else {return default_liquidation_penalty756;} } function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].fee;} else {return defaultArbiterFee;} } function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].liquidationRatio;} else {return default_liquidation_ratio475;} } function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].arbiter; } function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666()); } else { return funds[fund].balance; } } function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING if (compoundSet) { return cToken.EXCHANGERATECURRENT666(); } else { return 0; } } function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING return bools[fund].custom; } function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING return secretHashes[addr_].length; } function CREATE943( //inject NONSTANDARD NAMING uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years" ); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].arbiter = arbiter_; bools[fund].custom = false; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function CREATECUSTOM959( //inject NONSTANDARD NAMING uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 liquidationRatio_, uint256 interest_, uint256 penalty_, uint256 fee_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years" ); require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur"); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; funds[fund].arbiter = arbiter_; bools[fund].custom = true; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens"); if (bools[fund].compoundEnabled) { MINTCTOKEN703(address(token), address(cToken), amount_); uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666()); funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);} } else { funds[fund].balance = ADD803(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit DEPOSIT856(fund, amount_); } function UPDATE438( //inject NONSTANDARD NAMING bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_ ) public { require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund"); require( ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66, "Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years" ); funds[fund].maxLoanDur = maxLoanDur_; funds[fund].fundExpiry = fundExpiry_; funds[fund].arbiter = arbiter_; emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_); } function UPDATECUSTOM705( //inject NONSTANDARD NAMING bytes32 fund, uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 interest_, uint256 penalty_, uint256 fee_, uint256 liquidationRatio_, address arbiter_ ) external { require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund"); require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur"); UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_); funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; } function REQUEST711( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_, bytes32[8] calldata secretHashes_, bytes calldata pubKeyA_, bytes calldata pubKeyB_ ) external returns (bytes32 loanIndex) { require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request"); require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance"); require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt"); require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt"); require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur"); require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry"); require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero"); require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero"); require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero"); require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero"); require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero"); loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_); LOANUPDATEMARKETLIQUIDITY912(fund, amount_); loans.FUND172(loanIndex); emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); } function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING WITHDRAWTO298(fund, amount_, msg.sender); } function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens"); require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance"); if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit WITHDRAW160(fund, amount_, recipient_); } function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING for (uint i = 0; i < secretHashes_.length; i++) { secretHashes[msg.sender].push(secretHashes_[i]); } } function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING pubKeys[msg.sender] = pubKey_; } function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured"); require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled"); require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound"); uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); MINTCTOKEN703(address(token), address(cToken), funds[fund].balance); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore); tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance); cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn); bools[fund].compoundEnabled = true; funds[fund].balance = 0; funds[fund].cBalance = cTokenToReturn; emit ENABLECOMPOUND170(fund); } function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled"); require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound"); uint256 balanceBefore = token.BALANCEOF227(address(this)); REDEEMCTOKEN224(address(cToken), funds[fund].cBalance); uint256 balanceAfter = token.BALANCEOF227(address(this)); uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore); tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn); cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance); bools[fund].compoundEnabled = false; funds[fund].cBalance = 0; funds[fund].balance = tokenToReturn; emit DISABLECOMPOUND118(fund); } function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this"); totalBorrow = SUB97(totalBorrow, amount_); } function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725())); if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) { uint256 utilizationRatio; if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));} if (utilizationRatio > lastUtilizationRatio) { uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio); globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } else { uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio); globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); lastGlobalInterestUpdated = now; lastUtilizationRatio = utilizationRatio; } } function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_); } function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING if (value == 0) { if (addNow) { return now + max_loan_length66; } return max_loan_length66; } return value; } function CREATELOAN338( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_ ) private returns (bytes32 loanIndex) { loanIndex = loans.CREATE943( now + loanDur_, [borrower_, LENDER92(fund), funds[fund].arbiter], [ amount_, CALCINTEREST818(amount_, INTEREST523(fund), loanDur_), CALCINTEREST818(amount_, PENALTY434(fund), loanDur_), CALCINTEREST818(amount_, FEE426(fund), loanDur_), collateral_, LIQUIDATIONRATIO684(fund), requestTimestamp_ ], fund ); } function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING bytes32 fund, bytes32 loan, bytes32[8] memory secretHashes_, bytes memory pubKeyA_, bytes memory pubKeyB_ ) private { loans.SETSECRETHASHES742( loan, [ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ], [ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ], GETSECRETHASHESFORLOAN447(ARBITER4(fund)), pubKeyA_, pubKeyB_, pubKeys[ARBITER4(fund)] ); } function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) { totalBorrow = ADD803(totalBorrow, amount_); CALCGLOBALINTEREST773(); } } function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4); require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated"); return [ secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)] ]; } }
inject NONSTANDARD NAMING
function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
1,784,029
// SPDX-License-Identifier: AGPL-3.0-only /** * DepositBoxEth.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../DepositBox.sol"; import "../../Messages.sol"; // This contract runs on the main net and accepts deposits contract DepositBoxEth is DepositBox { using AddressUpgradeable for address payable; mapping(address => uint256) public approveTransfers; mapping(bytes32 => uint256) public transferredAmount; receive() external payable { revert("Use deposit function"); } function deposit(string memory schainName) external payable rightTransaction(schainName, msg.sender) whenNotKilled(keccak256(abi.encodePacked(schainName))) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); address contractReceiver = schainLinks[schainHash]; require(contractReceiver != address(0), "Unconnected chain"); if (!linker.interchainConnections(schainHash)) _saveTransferredAmount(schainHash, msg.value); messageProxy.postOutgoingMessage( schainHash, contractReceiver, Messages.encodeTransferEthMessage(msg.sender, msg.value) ); } function postMessage( bytes32 schainHash, address sender, bytes calldata data ) external override onlyMessageProxy whenNotKilled(schainHash) checkReceiverChain(schainHash, sender) returns (address) { Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data); require( message.amount <= address(this).balance, "Not enough money to finish this transaction" ); approveTransfers[message.receiver] += message.amount; if (!linker.interchainConnections(schainHash)) _removeTransferredAmount(schainHash, message.amount); return message.receiver; } /** * @dev Transfers a user's ETH. * * Requirements: * * - LockAndDataForMainnet must have sufficient ETH. * - User must be approved for ETH transfer. */ function getMyEth() external { require( address(this).balance >= approveTransfers[msg.sender], "Not enough ETH in DepositBox" ); require(approveTransfers[msg.sender] > 0, "User has insufficient ETH"); uint256 amount = approveTransfers[msg.sender]; approveTransfers[msg.sender] = 0; payable(msg.sender).sendValue(amount); } function getFunds(string calldata schainName, address payable receiver, uint amount) external onlySchainOwner(schainName) whenKilled(keccak256(abi.encodePacked(schainName))) { require(receiver != address(0), "Receiver address has to be set"); bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(transferredAmount[schainHash] >= amount, "Incorrect amount"); _removeTransferredAmount(schainHash, amount); receiver.sendValue(amount); } /// Create a new deposit box function initialize( IContractManager contractManagerOfSkaleManagerValue, Linker linkerValue, MessageProxyForMainnet messageProxyValue ) public override initializer { DepositBox.initialize(contractManagerOfSkaleManagerValue, linkerValue, messageProxyValue); } function _saveTransferredAmount(bytes32 schainHash, uint256 amount) private { transferredAmount[schainHash] += amount; } function _removeTransferredAmount(bytes32 schainHash, uint256 amount) private { transferredAmount[schainHash] -= amount; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: AGPL-3.0-only /** * DepositBox.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "./Linker.sol"; import "./MessageProxyForMainnet.sol"; /** * @title ProxyConnectorMainnet - connected module for Upgradeable approach, knows ContractManager * @author Artem Payvin */ abstract contract DepositBox is IMessageReceiver, Twin { Linker public linker; mapping(bytes32 => bool) private _automaticDeploy; bytes32 public constant DEPOSIT_BOX_MANAGER_ROLE = keccak256("DEPOSIT_BOX_MANAGER_ROLE"); modifier whenNotKilled(bytes32 schainHash) { require(linker.isNotKilled(schainHash), "Schain is killed"); _; } modifier whenKilled(bytes32 schainHash) { require(!linker.isNotKilled(schainHash), "Schain is not killed"); _; } modifier rightTransaction(string memory schainName, address to) { require( keccak256(abi.encodePacked(schainName)) != keccak256(abi.encodePacked("Mainnet")), "SKALE chain name cannot be Mainnet" ); require(to != address(0), "Receiver address cannot be null"); _; } modifier checkReceiverChain(bytes32 schainHash, address sender) { require( schainHash != keccak256(abi.encodePacked("Mainnet")) && sender == schainLinks[schainHash], "Receiver chain is incorrect" ); _; } /** * @dev Allows Schain owner turn on whitelist of tokens. */ function enableWhitelist(string memory schainName) external onlySchainOwner(schainName) { _automaticDeploy[keccak256(abi.encodePacked(schainName))] = false; } /** * @dev Allows Schain owner turn off whitelist of tokens. */ function disableWhitelist(string memory schainName) external onlySchainOwner(schainName) { _automaticDeploy[keccak256(abi.encodePacked(schainName))] = true; } function initialize( IContractManager contractManagerOfSkaleManagerValue, Linker newLinker, MessageProxyForMainnet messageProxyValue ) public virtual initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, address(newLinker)); linker = newLinker; } /** * @dev Returns is whitelist enabled on schain */ function isWhitelisted(string memory schainName) public view returns (bool) { return !_automaticDeploy[keccak256(abi.encodePacked(schainName))]; } } // SPDX-License-Identifier: AGPL-3.0-only /** * Messages.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaeiv * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; library Messages { enum MessageType { EMPTY, TRANSFER_ETH, TRANSFER_ERC20, TRANSFER_ERC20_AND_TOTAL_SUPPLY, TRANSFER_ERC20_AND_TOKEN_INFO, TRANSFER_ERC721, TRANSFER_ERC721_AND_TOKEN_INFO, USER_STATUS, INTERCHAIN_CONNECTION, TRANSFER_ERC1155, TRANSFER_ERC1155_AND_TOKEN_INFO, TRANSFER_ERC1155_BATCH, TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO } struct BaseMessage { MessageType messageType; } struct TransferEthMessage { BaseMessage message; address receiver; uint256 amount; } struct UserStatusMessage { BaseMessage message; address receiver; bool isActive; } struct TransferErc20Message { BaseMessage message; address token; address receiver; uint256 amount; } struct Erc20TokenInfo { string name; uint8 decimals; string symbol; } struct TransferErc20AndTotalSupplyMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; } struct TransferErc20AndTokenInfoMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; Erc20TokenInfo tokenInfo; } struct TransferErc721Message { BaseMessage message; address token; address receiver; uint256 tokenId; } struct Erc721TokenInfo { string name; string symbol; } struct TransferErc721AndTokenInfoMessage { TransferErc721Message baseErc721transfer; Erc721TokenInfo tokenInfo; } struct InterchainConnectionMessage { BaseMessage message; bool isAllowed; } struct TransferErc1155Message { BaseMessage message; address token; address receiver; uint256 id; uint256 amount; } struct TransferErc1155BatchMessage { BaseMessage message; address token; address receiver; uint256[] ids; uint256[] amounts; } struct Erc1155TokenInfo { string uri; } struct TransferErc1155AndTokenInfoMessage { TransferErc1155Message baseErc1155transfer; Erc1155TokenInfo tokenInfo; } struct TransferErc1155BatchAndTokenInfoMessage { TransferErc1155BatchMessage baseErc1155Batchtransfer; Erc1155TokenInfo tokenInfo; } function getMessageType(bytes calldata data) internal pure returns (MessageType) { uint256 firstWord = abi.decode(data, (uint256)); if (firstWord % 32 == 0) { return getMessageType(data[firstWord:]); } else { return abi.decode(data, (Messages.MessageType)); } } function encodeTransferEthMessage(address receiver, uint256 amount) internal pure returns (bytes memory) { TransferEthMessage memory message = TransferEthMessage( BaseMessage(MessageType.TRANSFER_ETH), receiver, amount ); return abi.encode(message); } function decodeTransferEthMessage( bytes calldata data ) internal pure returns (TransferEthMessage memory) { require(getMessageType(data) == MessageType.TRANSFER_ETH, "Message type is not ETH transfer"); return abi.decode(data, (TransferEthMessage)); } function encodeTransferErc20Message( address token, address receiver, uint256 amount ) internal pure returns (bytes memory) { TransferErc20Message memory message = TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20), token, receiver, amount ); return abi.encode(message); } function encodeTransferErc20AndTotalSupplyMessage( address token, address receiver, uint256 amount, uint256 totalSupply ) internal pure returns (bytes memory) { TransferErc20AndTotalSupplyMessage memory message = TransferErc20AndTotalSupplyMessage( TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY), token, receiver, amount ), totalSupply ); return abi.encode(message); } function decodeTransferErc20Message( bytes calldata data ) internal pure returns (TransferErc20Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC20, "Message type is not ERC20 transfer"); return abi.decode(data, (TransferErc20Message)); } function decodeTransferErc20AndTotalSupplyMessage( bytes calldata data ) internal pure returns (TransferErc20AndTotalSupplyMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY, "Message type is not ERC20 transfer and total supply" ); return abi.decode(data, (TransferErc20AndTotalSupplyMessage)); } function encodeTransferErc20AndTokenInfoMessage( address token, address receiver, uint256 amount, uint256 totalSupply, Erc20TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc20AndTokenInfoMessage memory message = TransferErc20AndTokenInfoMessage( TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20_AND_TOKEN_INFO), token, receiver, amount ), totalSupply, tokenInfo ); return abi.encode(message); } function decodeTransferErc20AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc20AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOKEN_INFO, "Message type is not ERC20 transfer with token info" ); return abi.decode(data, (TransferErc20AndTokenInfoMessage)); } function encodeTransferErc721Message( address token, address receiver, uint256 tokenId ) internal pure returns (bytes memory) { TransferErc721Message memory message = TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721), token, receiver, tokenId ); return abi.encode(message); } function decodeTransferErc721Message( bytes calldata data ) internal pure returns (TransferErc721Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC721, "Message type is not ERC721 transfer"); return abi.decode(data, (TransferErc721Message)); } function encodeTransferErc721AndTokenInfoMessage( address token, address receiver, uint256 tokenId, Erc721TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc721AndTokenInfoMessage memory message = TransferErc721AndTokenInfoMessage( TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721_AND_TOKEN_INFO), token, receiver, tokenId ), tokenInfo ); return abi.encode(message); } function decodeTransferErc721AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc721AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC721_AND_TOKEN_INFO, "Message type is not ERC721 transfer with token info" ); return abi.decode(data, (TransferErc721AndTokenInfoMessage)); } function encodeActivateUserMessage(address receiver) internal pure returns (bytes memory){ return _encodeUserStatusMessage(receiver, true); } function encodeLockUserMessage(address receiver) internal pure returns (bytes memory){ return _encodeUserStatusMessage(receiver, false); } function decodeUserStatusMessage(bytes calldata data) internal pure returns (UserStatusMessage memory) { require(getMessageType(data) == MessageType.USER_STATUS, "Message type is not User Status"); return abi.decode(data, (UserStatusMessage)); } function encodeInterchainConnectionMessage(bool isAllowed) internal pure returns (bytes memory) { InterchainConnectionMessage memory message = InterchainConnectionMessage( BaseMessage(MessageType.INTERCHAIN_CONNECTION), isAllowed ); return abi.encode(message); } function decodeInterchainConnectionMessage(bytes calldata data) internal pure returns (InterchainConnectionMessage memory) { require(getMessageType(data) == MessageType.INTERCHAIN_CONNECTION, "Message type is not Interchain connection"); return abi.decode(data, (InterchainConnectionMessage)); } function encodeTransferErc1155Message( address token, address receiver, uint256 id, uint256 amount ) internal pure returns (bytes memory) { TransferErc1155Message memory message = TransferErc1155Message( BaseMessage(MessageType.TRANSFER_ERC1155), token, receiver, id, amount ); return abi.encode(message); } function decodeTransferErc1155Message( bytes calldata data ) internal pure returns (TransferErc1155Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC1155, "Message type is not ERC1155 transfer"); return abi.decode(data, (TransferErc1155Message)); } function encodeTransferErc1155AndTokenInfoMessage( address token, address receiver, uint256 id, uint256 amount, Erc1155TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc1155AndTokenInfoMessage memory message = TransferErc1155AndTokenInfoMessage( TransferErc1155Message( BaseMessage(MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO), token, receiver, id, amount ), tokenInfo ); return abi.encode(message); } function decodeTransferErc1155AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc1155AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO, "Message type is not ERC1155AndTokenInfo transfer" ); return abi.decode(data, (TransferErc1155AndTokenInfoMessage)); } function encodeTransferErc1155BatchMessage( address token, address receiver, uint256[] memory ids, uint256[] memory amounts ) internal pure returns (bytes memory) { TransferErc1155BatchMessage memory message = TransferErc1155BatchMessage( BaseMessage(MessageType.TRANSFER_ERC1155_BATCH), token, receiver, ids, amounts ); return abi.encode(message); } function decodeTransferErc1155BatchMessage( bytes calldata data ) internal pure returns (TransferErc1155BatchMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH, "Message type is not ERC1155Batch transfer" ); return abi.decode(data, (TransferErc1155BatchMessage)); } function encodeTransferErc1155BatchAndTokenInfoMessage( address token, address receiver, uint256[] memory ids, uint256[] memory amounts, Erc1155TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc1155BatchAndTokenInfoMessage memory message = TransferErc1155BatchAndTokenInfoMessage( TransferErc1155BatchMessage( BaseMessage(MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO), token, receiver, ids, amounts ), tokenInfo ); return abi.encode(message); } function decodeTransferErc1155BatchAndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc1155BatchAndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO, "Message type is not ERC1155BatchAndTokenInfo transfer" ); return abi.decode(data, (TransferErc1155BatchAndTokenInfoMessage)); } function _encodeUserStatusMessage(address receiver, bool isActive) private pure returns (bytes memory) { UserStatusMessage memory message = UserStatusMessage( BaseMessage(MessageType.USER_STATUS), receiver, isActive ); return abi.encode(message); } } // SPDX-License-Identifier: AGPL-3.0-only /** * Linker.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../Messages.sol"; import "./Twin.sol"; import "./MessageProxyForMainnet.sol"; /** * @title Linker For Mainnet * @dev Runs on Mainnet, holds deposited ETH, and contains mappings and * balances of ETH tokens received through DepositBox. */ contract Linker is Twin { using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; enum KillProcess {NotKilled, PartiallyKilledBySchainOwner, PartiallyKilledByContractOwner, Killed} EnumerableSetUpgradeable.AddressSet private _mainnetContracts; mapping(bytes32 => bool) public interchainConnections; mapping(bytes32 => KillProcess) public statuses; modifier onlyLinker() { require(hasRole(LINKER_ROLE, msg.sender), "Linker role is required"); _; } function registerMainnetContract(address newMainnetContract) external onlyLinker { require(_mainnetContracts.add(newMainnetContract), "The contracts was not registered"); } function removeMainnetContract(address mainnetContract) external onlyLinker { require(_mainnetContracts.remove(mainnetContract), "The contract was not removed"); } function connectSchain(string calldata schainName, address[] calldata schainContracts) external onlyLinker { require(schainContracts.length == _mainnetContracts.length(), "Incorrect number of addresses"); for (uint i = 0; i < schainContracts.length; i++) { Twin(_mainnetContracts.at(i)).addSchainContract(schainName, schainContracts[i]); } messageProxy.addConnectedChain(schainName); } function allowInterchainConnections(string calldata schainName) external onlySchainOwner(schainName) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(statuses[schainHash] == KillProcess.NotKilled, "Schain is in kill process"); interchainConnections[schainHash] = true; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeInterchainConnectionMessage(true) ); } function kill(string calldata schainName) external { require(!interchainConnections[keccak256(abi.encodePacked(schainName))], "Interchain connections turned on"); bytes32 schainHash = keccak256(abi.encodePacked(schainName)); if (statuses[schainHash] == KillProcess.NotKilled) { if (hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) { statuses[schainHash] = KillProcess.PartiallyKilledByContractOwner; } else if (isSchainOwner(msg.sender, schainHash)) { statuses[schainHash] = KillProcess.PartiallyKilledBySchainOwner; } else { revert("Not allowed"); } } else if ( ( statuses[schainHash] == KillProcess.PartiallyKilledBySchainOwner && hasRole(DEFAULT_ADMIN_ROLE, msg.sender) ) || ( statuses[schainHash] == KillProcess.PartiallyKilledByContractOwner && isSchainOwner(msg.sender, schainHash) ) ) { statuses[schainHash] = KillProcess.Killed; } else { revert("Already killed or incorrect sender"); } } function disconnectSchain(string calldata schainName) external onlyLinker { uint length = _mainnetContracts.length(); for (uint i = 0; i < length; i++) { Twin(_mainnetContracts.at(i)).removeSchainContract(schainName); } messageProxy.removeConnectedChain(schainName); } function isNotKilled(bytes32 schainHash) external view returns (bool) { return statuses[schainHash] != KillProcess.Killed; } function hasMainnetContract(address mainnetContract) external view returns (bool) { return _mainnetContracts.contains(mainnetContract); } function hasSchain(string calldata schainName) external view returns (bool connected) { uint length = _mainnetContracts.length(); connected = messageProxy.isConnectedChain(schainName); for (uint i = 0; connected && i < length; i++) { connected = connected && Twin(_mainnetContracts.at(i)).hasSchainContract(schainName); } } function initialize( IContractManager contractManagerOfSkaleManagerValue, MessageProxyForMainnet messageProxyValue ) public override initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, msg.sender); _setupRole(LINKER_ROLE, address(this)); } } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "../interfaces/IMessageReceiver.sol"; import "../MessageProxy.sol"; import "./SkaleManagerClient.sol"; import "./CommunityPool.sol"; /** * @title Message Proxy for Mainnet * @dev Runs on Mainnet, contains functions to manage the incoming messages from * `targetSchainName` and outgoing messages to `fromSchainName`. Every SKALE chain with * IMA is therefore connected to MessageProxyForMainnet. * * Messages from SKALE chains are signed using BLS threshold signatures from the * nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet * messages do not need to be signed. */ contract MessageProxyForMainnet is SkaleManagerClient, MessageProxy { using AddressUpgradeable for address; /** * 16 Agents * Synchronize time with time.nist.gov * Every agent checks if it is his time slot * Time slots are in increments of 10 seconds * At the start of his slot each agent: * For each connected schain: * Read incoming counter on the dst chain * Read outgoing counter on the src chain * Calculate the difference outgoing - incoming * Call postIncomingMessages function passing (un)signed message array * ID of this schain, Chain 0 represents ETH mainnet, */ CommunityPool public communityPool; uint256 public headerMessageGasCost; uint256 public messageGasCost; event GasCostMessageHeaderWasChanged( uint256 oldValue, uint256 newValue ); event GasCostMessageWasChanged( uint256 oldValue, uint256 newValue ); /** * @dev Allows LockAndData to add a `schainName`. * * Requirements: * * - `msg.sender` must be SKALE Node address. * - `schainName` must not be "Mainnet". * - `schainName` must not already be added. */ function addConnectedChain(string calldata schainName) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(schainHash != MAINNET_HASH, "SKALE chain name is incorrect"); _addConnectedChain(schainHash); } function setCommunityPool(CommunityPool newCommunityPoolAddress) external { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller"); require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set"); communityPool = newCommunityPoolAddress; } function registerExtraContract(string memory schainName, address extraContract) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not enough permissions to register extra contract" ); require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet"); _registerExtraContract(schainHash, extraContract); } function removeExtraContract(string memory schainName, address extraContract) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not enough permissions to register extra contract" ); require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet"); _removeExtraContract(schainHash, extraContract); } /** * @dev Posts incoming message from `fromSchainName`. * * Requirements: * * - `msg.sender` must be authorized caller. * - `fromSchainName` must be initialized. * - `startingCounter` must be equal to the chain's incoming message counter. * - If destination chain is Mainnet, message signature must be valid. */ function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external override { uint256 gasTotal = gasleft(); bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName)); require(connectedChains[fromSchainHash].inited, "Chain is not initialized"); require(messages.length <= MESSAGES_LENGTH, "Too many messages"); require( startingCounter == connectedChains[fromSchainHash].incomingMessageCounter, "Starting counter is not equal to incoming message counter"); require(_verifyMessages(fromSchainName, _hashedArray(messages), sign), "Signature is not verified"); uint additionalGasPerMessage = (gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length; for (uint256 i = 0; i < messages.length; i++) { gasTotal = gasleft(); address receiver = _callReceiverContract(fromSchainHash, messages[i], startingCounter + i); if (receiver == address(0)) continue; communityPool.refundGasByUser( fromSchainHash, payable(msg.sender), receiver, gasTotal - gasleft() + additionalGasPerMessage ); } connectedChains[fromSchainHash].incomingMessageCounter += messages.length; } /** * @dev Sets headerMessageGasCost to a new value * * Requirements: * * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE. */ function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external onlyConstantSetter { emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost); headerMessageGasCost = newHeaderMessageGasCost; } /** * @dev Sets messageGasCost to a new value * * Requirements: * * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE. */ function setNewMessageGasCost(uint256 newMessageGasCost) external onlyConstantSetter { emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost); messageGasCost = newMessageGasCost; } /** * @dev Checks whether chain is currently connected. * * Note: Mainnet chain does not have a public key, and is implicitly * connected to MessageProxy. * * Requirements: * * - `schainName` must not be Mainnet. */ function isConnectedChain( string memory schainName ) public view override returns (bool) { require(keccak256(abi.encodePacked(schainName)) != MAINNET_HASH, "Schain id can not be equal Mainnet"); return super.isConnectedChain(schainName); } // Create a new message proxy function initialize(IContractManager contractManagerOfSkaleManagerValue) public virtual override initializer { SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue); MessageProxy.initializeMessageProxy(1e6); headerMessageGasCost = 70000; messageGasCost = 8790; } /** * @dev Converts calldata structure to memory structure and checks * whether message BLS signature is valid. */ function _verifyMessages( string calldata fromSchainName, bytes32 hashedMessages, MessageProxyForMainnet.Signature calldata sign ) internal view returns (bool) { return ISchains( contractManagerOfSkaleManager.getContract("Schains") ).verifySchainSignature( sign.blsSignature[0], sign.blsSignature[1], hashedMessages, sign.counter, sign.hashA, sign.hashB, fromSchainName ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: AGPL-3.0-only /** * Twin.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * @author Dmytro Stebaiev * @author Vadim Yavorsky * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "./MessageProxyForMainnet.sol"; import "./SkaleManagerClient.sol"; abstract contract Twin is SkaleManagerClient { MessageProxyForMainnet public messageProxy; mapping(bytes32 => address) public schainLinks; bytes32 public constant LINKER_ROLE = keccak256("LINKER_ROLE"); modifier onlyMessageProxy() { require(msg.sender == address(messageProxy), "Sender is not a MessageProxy"); _; } /** * @dev Binds a contract on mainnet with his twin on schain * * Requirements: * * - `msg.sender` must be schain owner or has required role. * - SKALE chain must not already be added. * - Address of contract on schain must be non-zero. */ function addSchainContract(string calldata schainName, address contractReceiver) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(LINKER_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not authorized caller" ); require(schainLinks[schainHash] == address(0), "SKALE chain is already set"); require(contractReceiver != address(0), "Incorrect address of contract receiver on Schain"); schainLinks[schainHash] = contractReceiver; } /** * @dev Removes connection with contract on schain * * Requirements: * * - `msg.sender` must be schain owner or has required role * - SKALE chain must already be set. */ function removeSchainContract(string calldata schainName) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(LINKER_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not authorized caller" ); require(schainLinks[schainHash] != address(0), "SKALE chain is not set"); delete schainLinks[schainHash]; } function hasSchainContract(string calldata schainName) external view returns (bool) { return schainLinks[keccak256(abi.encodePacked(schainName))] != address(0); } function initialize( IContractManager contractManagerOfSkaleManagerValue, MessageProxyForMainnet newMessageProxy ) public virtual initializer { SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue); messageProxy = newMessageProxy; } } // SPDX-License-Identifier: AGPL-3.0-only /** * SkaleManagerClient.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; /** * @title SkaleManagerClient - contract that knows ContractManager * and makes calls to SkaleManager contracts * @author Artem Payvin * @author Dmytro Stebaiev */ contract SkaleManagerClient is Initializable, AccessControlEnumerableUpgradeable { IContractManager public contractManagerOfSkaleManager; modifier onlySchainOwner(string memory schainName) { require( isSchainOwner(msg.sender, keccak256(abi.encodePacked(schainName))), "Sender is not an Schain owner" ); _; } /** * @dev Checks whether sender is owner of SKALE chain */ function isSchainOwner(address sender, bytes32 schainHash) public view returns (bool) { address skaleChainsInternal = contractManagerOfSkaleManager.getContract("SchainsInternal"); return ISchainsInternal(skaleChainsInternal).isOwnerAddress(sender, schainHash); } /** * @dev initialize - sets current address of ContractManager of SkaleManager * @param newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager */ function initialize( IContractManager newContractManagerOfSkaleManager ) public virtual initializer { AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); contractManagerOfSkaleManager = newContractManagerOfSkaleManager; } } // SPDX-License-Identifier: AGPL-3.0-only /* IWallets - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IWallets { function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external; function rechargeSchainWallet(bytes32 schainId) external payable; } // SPDX-License-Identifier: AGPL-3.0-only /* ISchains.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchains { function verifySchainSignature( uint256 signA, uint256 signB, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string calldata schainName ) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * IMessageReceiver.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; interface IMessageReceiver { function postMessage( bytes32 schainHash, address sender, bytes calldata data ) external returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxy.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "./interfaces/IMessageReceiver.sol"; abstract contract MessageProxy is AccessControlEnumerableUpgradeable { using AddressUpgradeable for address; bytes32 public constant MAINNET_HASH = keccak256(abi.encodePacked("Mainnet")); bytes32 public constant CHAIN_CONNECTOR_ROLE = keccak256("CHAIN_CONNECTOR_ROLE"); bytes32 public constant EXTRA_CONTRACT_REGISTRAR_ROLE = keccak256("EXTRA_CONTRACT_REGISTRAR_ROLE"); bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE"); uint256 public constant MESSAGES_LENGTH = 10; struct ConnectedChainInfo { // message counters start with 0 uint256 incomingMessageCounter; uint256 outgoingMessageCounter; bool inited; } struct Message { address sender; address destinationContract; bytes data; } struct Signature { uint256[2] blsSignature; uint256 hashA; uint256 hashB; uint256 counter; } // schainHash => ConnectedChainInfo mapping(bytes32 => ConnectedChainInfo) public connectedChains; // schainHash => contract address => allowed mapping(bytes32 => mapping(address => bool)) public registryContracts; uint256 public gasLimit; /** * @dev Emitted for every outgoing message to `dstChain`. */ event OutgoingMessage( bytes32 indexed dstChainHash, uint256 indexed msgCounter, address indexed srcContract, address dstContract, bytes data ); event PostMessageError( uint256 indexed msgCounter, bytes message ); event GasLimitWasChanged( uint256 oldValue, uint256 newValue ); modifier onlyChainConnector() { require(hasRole(CHAIN_CONNECTOR_ROLE, msg.sender), "CHAIN_CONNECTOR_ROLE is required"); _; } modifier onlyExtraContractRegistrar() { require(hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender), "EXTRA_CONTRACT_REGISTRAR_ROLE is required"); _; } modifier onlyConstantSetter() { require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "Not enough permissions to set constant"); _; } function initializeMessageProxy(uint newGasLimit) public initializer { AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(CHAIN_CONNECTOR_ROLE, msg.sender); _setupRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender); _setupRole(CONSTANT_SETTER_ROLE, msg.sender); gasLimit = newGasLimit; } // Registration state detection function isConnectedChain( string memory schainName ) public view virtual returns (bool) { return connectedChains[keccak256(abi.encodePacked(schainName))].inited; } /** * @dev Allows LockAndData to add a `schainName`. * * Requirements: * * - `msg.sender` must be SKALE Node address. * - `schainName` must not be "Mainnet". * - `schainName` must not already be added. */ function addConnectedChain(string calldata schainName) external virtual; /** * @dev Allows LockAndData to remove connected chain from this contract. * * Requirements: * * - `msg.sender` must be LockAndData contract. * - `schainName` must be initialized. */ function removeConnectedChain(string memory schainName) public virtual onlyChainConnector { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(connectedChains[schainHash].inited, "Chain is not initialized"); delete connectedChains[schainHash]; } /** * @dev Sets gasLimit to a new value * * Requirements: * * - `msg.sender` must be granted CONSTANT_SETTER_ROLE. */ function setNewGasLimit(uint256 newGasLimit) external onlyConstantSetter { emit GasLimitWasChanged(gasLimit, newGasLimit); gasLimit = newGasLimit; } /** * @dev Posts message from this contract to `targetSchainName` MessageProxy contract. * This is called by a smart contract to make a cross-chain call. * * Requirements: * * - `targetSchainName` must be initialized. */ function postOutgoingMessage( bytes32 targetChainHash, address targetContract, bytes memory data ) public virtual { require(connectedChains[targetChainHash].inited, "Destination chain is not initialized"); require( registryContracts[bytes32(0)][msg.sender] || registryContracts[targetChainHash][msg.sender], "Sender contract is not registered" ); emit OutgoingMessage( targetChainHash, connectedChains[targetChainHash].outgoingMessageCounter, msg.sender, targetContract, data ); connectedChains[targetChainHash].outgoingMessageCounter += 1; } function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external virtual; function registerExtraContractForAll(address extraContract) external onlyExtraContractRegistrar { require(extraContract.isContract(), "Given address is not a contract"); require(!registryContracts[bytes32(0)][extraContract], "Extra contract is already registered"); registryContracts[bytes32(0)][extraContract] = true; } function removeExtraContractForAll(address extraContract) external onlyExtraContractRegistrar { require(registryContracts[bytes32(0)][extraContract], "Extra contract is not registered"); delete registryContracts[bytes32(0)][extraContract]; } /** * @dev Checks whether contract is currently connected to * send messages to chain or receive messages from chain. */ function isContractRegistered( string calldata schainName, address contractAddress ) external view returns (bool) { return registryContracts[keccak256(abi.encodePacked(schainName))][contractAddress] || registryContracts[bytes32(0)][contractAddress]; } /** * @dev Returns number of outgoing messages to some schain * * Requirements: * * - `targetSchainName` must be initialized. */ function getOutgoingMessagesCounter(string calldata targetSchainName) external view returns (uint256) { bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName)); require(connectedChains[dstChainHash].inited, "Destination chain is not initialized"); return connectedChains[dstChainHash].outgoingMessageCounter; } /** * @dev Returns number of incoming messages from some schain * * Requirements: * * - `fromSchainName` must be initialized. */ function getIncomingMessagesCounter(string calldata fromSchainName) external view returns (uint256) { bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName)); require(connectedChains[srcChainHash].inited, "Source chain is not initialized"); return connectedChains[srcChainHash].incomingMessageCounter; } // private function _addConnectedChain(bytes32 schainHash) internal onlyChainConnector { require(!connectedChains[schainHash].inited,"Chain is already connected"); connectedChains[schainHash] = ConnectedChainInfo({ incomingMessageCounter: 0, outgoingMessageCounter: 0, inited: true }); } function _callReceiverContract( bytes32 schainHash, Message calldata message, uint counter ) internal returns (address) { try IMessageReceiver(message.destinationContract).postMessage{gas: gasLimit}( schainHash, message.sender, message.data ) returns (address receiver) { return receiver; } catch Error(string memory reason) { emit PostMessageError( counter, bytes(reason) ); return address(0); } catch (bytes memory revertData) { emit PostMessageError( counter, revertData ); return address(0); } } function _registerExtraContract( bytes32 chainHash, address extraContract ) internal { require(extraContract.isContract(), "Given address is not a contract"); require(!registryContracts[chainHash][extraContract], "Extra contract is already registered"); require(!registryContracts[bytes32(0)][extraContract], "Extra contract is already registered for all chains"); registryContracts[chainHash][extraContract] = true; } function _removeExtraContract( bytes32 chainHash, address extraContract ) internal { require(registryContracts[chainHash][extraContract], "Extra contract is not registered"); delete registryContracts[chainHash][extraContract]; } /** * @dev Returns hash of message array. */ function _hashedArray(Message[] calldata messages) internal pure returns (bytes32) { bytes memory data; for (uint256 i = 0; i < messages.length; i++) { data = abi.encodePacked( data, bytes32(bytes20(messages[i].sender)), bytes32(bytes20(messages[i].destinationContract)), messages[i].data ); } return keccak256(data); } } // SPDX-License-Identifier: AGPL-3.0-only /* CommunityPool.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "../Messages.sol"; import "./MessageProxyForMainnet.sol"; import "./Linker.sol"; /** * @title CommunityPool * @dev Contract contains logic to perform automatic self-recharging ether for nodes */ contract CommunityPool is Twin { using AddressUpgradeable for address payable; bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE"); mapping(address => mapping(bytes32 => uint)) private _userWallets; mapping(address => mapping(bytes32 => bool)) public activeUsers; uint public minTransactionGas; event MinTransactionGasWasChanged( uint oldValue, uint newValue ); function initialize( IContractManager contractManagerOfSkaleManagerValue, Linker linker, MessageProxyForMainnet messageProxyValue ) external initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, address(linker)); minTransactionGas = 1e6; } function refundGasByUser( bytes32 schainHash, address payable node, address user, uint gas ) external onlyMessageProxy { require(activeUsers[user][schainHash], "User should be active"); require(node != address(0), "Node address must be set"); uint amount = tx.gasprice * gas; _userWallets[user][schainHash] = _userWallets[user][schainHash] - amount; if (_userWallets[user][schainHash] < minTransactionGas * tx.gasprice) { activeUsers[user][schainHash] = false; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeLockUserMessage(user) ); } node.sendValue(amount); } /** * @dev Allows `msg.sender` to recharge their wallet for further gas reimbursement. * * Requirements: * * - 'msg.sender` should recharge their gas wallet for amount that enough to reimburse any * transaction from schain to mainnet. */ function rechargeUserWallet(string calldata schainName, address user) external payable { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( msg.value + _userWallets[user][schainHash] >= minTransactionGas * tx.gasprice, "Not enough ETH for transaction" ); _userWallets[user][schainHash] = _userWallets[user][schainHash] + msg.value; if (!activeUsers[user][schainHash]) { activeUsers[user][schainHash] = true; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeActivateUserMessage(user) ); } } function withdrawFunds(string calldata schainName, uint amount) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(amount <= _userWallets[msg.sender][schainHash], "Balance is too low"); _userWallets[msg.sender][schainHash] = _userWallets[msg.sender][schainHash] - amount; if ( _userWallets[msg.sender][schainHash] < minTransactionGas * tx.gasprice && activeUsers[msg.sender][schainHash] ) { activeUsers[msg.sender][schainHash] = false; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeLockUserMessage(msg.sender) ); } payable(msg.sender).sendValue(amount); } function setMinTransactionGas(uint newMinTransactionGas) external { require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "CONSTANT_SETTER_ROLE is required"); emit MinTransactionGasWasChanged(minTransactionGas, newMinTransactionGas); minTransactionGas = newMinTransactionGas; } function getBalance(address user, string calldata schainName) external view returns (uint) { return _userWallets[user][keccak256(abi.encodePacked(schainName))]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchainsInternal - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchainsInternal { function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool); function isOwnerAddress(address from, bytes32 schainId) external view returns (bool); }
Posts incoming message from `fromSchainName`. Requirements: - `msg.sender` must be authorized caller. - `fromSchainName` must be initialized. - `startingCounter` must be equal to the chain's incoming message counter. - If destination chain is Mainnet, message signature must be valid./
function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external override { uint256 gasTotal = gasleft(); bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName)); require(connectedChains[fromSchainHash].inited, "Chain is not initialized"); require(messages.length <= MESSAGES_LENGTH, "Too many messages"); require( startingCounter == connectedChains[fromSchainHash].incomingMessageCounter, "Starting counter is not equal to incoming message counter"); require(_verifyMessages(fromSchainName, _hashedArray(messages), sign), "Signature is not verified"); uint additionalGasPerMessage = (gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length; for (uint256 i = 0; i < messages.length; i++) { gasTotal = gasleft(); address receiver = _callReceiverContract(fromSchainHash, messages[i], startingCounter + i); if (receiver == address(0)) continue; communityPool.refundGasByUser( fromSchainHash, payable(msg.sender), receiver, gasTotal - gasleft() + additionalGasPerMessage ); } connectedChains[fromSchainHash].incomingMessageCounter += messages.length; }
142,394
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IERC20Extended.sol"; import "./interfaces/ILockManager.sol"; import "./lib/Initializable.sol"; /** * @title EdenNetwork * @dev It is VERY IMPORTANT that modifications to this contract do not change the storage layout of the existing variables. * Be especially careful when importing any external contracts/libraries. * If you do not know what any of this means, BACK AWAY FROM THE CODE NOW!! */ contract EdenNetwork is Initializable { /// @notice Slot bid details struct Bid { address bidder; uint16 taxNumerator; uint16 taxDenominator; uint64 periodStart; uint128 bidAmount; } /// @notice Expiration timestamp of current bid for specified slot index mapping (uint8 => uint64) public slotExpiration; /// @dev Address to be prioritized for given slot mapping (uint8 => address) private _slotDelegate; /// @dev Address that owns a given slot and is able to set the slot delegate mapping (uint8 => address) private _slotOwner; /// @notice Current bid for given slot mapping (uint8 => Bid) public slotBid; /// @notice Staked balance in contract mapping (address => uint128) public stakedBalance; /// @notice Balance in contract that was previously used for bid mapping (address => uint128) public lockedBalance; /// @notice Token used to reserve slot IERC20Extended public token; /// @notice Lock Manager contract ILockManager public lockManager; /// @notice Admin that can set the contract tax rate address public admin; /// @notice Numerator for tax rate uint16 public taxNumerator; /// @notice Denominator for tax rate uint16 public taxDenominator; /// @notice Minimum bid to reserve slot uint128 public MIN_BID; /// @dev Reentrancy var used like bool, but with refunds uint256 private _NOT_ENTERED; /// @dev Reentrancy var used like bool, but with refunds uint256 private _ENTERED; /// @dev Reentrancy status uint256 private _status; /// @notice Only admin can call modifier onlyAdmin() { require(msg.sender == admin, "not admin"); _; } /// @notice Only slot owner can call modifier onlySlotOwner(uint8 slot) { require(msg.sender == slotOwner(slot), "not slot owner"); _; } /// @notice Reentrancy prevention modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "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; } /// @notice Event emitted when admin is updated event AdminUpdated(address indexed newAdmin, address indexed oldAdmin); /// @notice Event emitted when the tax rate is updated event TaxRateUpdated(uint16 newNumerator, uint16 newDenominator, uint16 oldNumerator, uint16 oldDenominator); /// @notice Event emitted when slot is claimed event SlotClaimed(uint8 indexed slot, address indexed owner, address indexed delegate, uint128 newBidAmount, uint128 oldBidAmount, uint16 taxNumerator, uint16 taxDenominator); /// @notice Event emitted when slot delegate is updated event SlotDelegateUpdated(uint8 indexed slot, address indexed owner, address indexed newDelegate, address oldDelegate); /// @notice Event emitted when a user stakes tokens event Stake(address indexed staker, uint256 stakeAmount); /// @notice Event emitted when a user unstakes tokens event Unstake(address indexed staker, uint256 unstakedAmount); /// @notice Event emitted when a user withdraws locked tokens event Withdraw(address indexed withdrawer, uint256 withdrawalAmount); /** * @notice Initialize EdenNetwork contract * @param _token Token address * @param _lockManager Lock Manager address * @param _admin Admin address * @param _taxNumerator Numerator for tax rate * @param _taxDenominator Denominator for tax rate */ function initialize( IERC20Extended _token, ILockManager _lockManager, address _admin, uint16 _taxNumerator, uint16 _taxDenominator ) public initializer { token = _token; lockManager = _lockManager; admin = _admin; emit AdminUpdated(_admin, address(0)); taxNumerator = _taxNumerator; taxDenominator = _taxDenominator; emit TaxRateUpdated(_taxNumerator, _taxDenominator, 0, 0); MIN_BID = 10000000000000000; _NOT_ENTERED = 1; _ENTERED = 2; _status = _NOT_ENTERED; } /** * @notice Get current owner of slot * @param slot Slot index * @return Slot owner address */ function slotOwner(uint8 slot) public view returns (address) { if(slotForeclosed(slot)) { return address(0); } return _slotOwner[slot]; } /** * @notice Get current slot delegate * @param slot Slot index * @return Slot delegate address */ function slotDelegate(uint8 slot) public view returns (address) { if(slotForeclosed(slot)) { return address(0); } return _slotDelegate[slot]; } /** * @notice Get current cost to claim slot * @param slot Slot index * @return Slot cost */ function slotCost(uint8 slot) external view returns (uint128) { if(slotForeclosed(slot)) { return MIN_BID; } Bid memory currentBid = slotBid[slot]; return currentBid.bidAmount * 110 / 100; } /** * @notice Claim slot * @param slot Slot index * @param bid Bid amount * @param delegate Delegate for slot */ function claimSlot( uint8 slot, uint128 bid, address delegate ) external nonReentrant { _claimSlot(slot, bid, delegate); } /** * @notice Claim slot using permit for approval * @param slot Slot index * @param bid Bid amount * @param delegate Delegate for slot * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function claimSlotWithPermit( uint8 slot, uint128 bid, address delegate, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { token.permit(msg.sender, address(this), bid, deadline, v, r, s); _claimSlot(slot, bid, delegate); } /** * @notice Get untaxed balance for current slot bid * @param slot Slot index * @return balance Slot balance */ function slotBalance(uint8 slot) public view returns (uint128 balance) { Bid memory currentBid = slotBid[slot]; if (currentBid.bidAmount == 0 || slotForeclosed(slot)) { return 0; } else if (block.timestamp == currentBid.periodStart) { return currentBid.bidAmount; } else { return uint128(uint256(currentBid.bidAmount) - (uint256(currentBid.bidAmount) * (block.timestamp - currentBid.periodStart) * currentBid.taxNumerator / (uint256(currentBid.taxDenominator) * 86400))); } } /** * @notice Returns true if a given slot bid has expired * @param slot Slot index * @return True if slot is foreclosed */ function slotForeclosed(uint8 slot) public view returns (bool) { if(slotExpiration[slot] <= block.timestamp) { return true; } return false; } /** * @notice Stake tokens * @param amount Amount of tokens to stake */ function stake(uint128 amount) external nonReentrant { _stake(amount); } /** * @notice Stake tokens using permit for approval * @param amount Amount of tokens to stake * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function stakeWithPermit( uint128 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { token.permit(msg.sender, address(this), amount, deadline, v, r, s); _stake(amount); } /** * @notice Unstake tokens * @param amount Amount of tokens to unstake */ function unstake(uint128 amount) external nonReentrant { require(stakedBalance[msg.sender] >= amount, "amount > unlocked balance"); lockManager.removeVotingPower(msg.sender, address(token), amount); stakedBalance[msg.sender] -= amount; token.transfer(msg.sender, amount); emit Unstake(msg.sender, amount); } /** * @notice Withdraw locked tokens * @param amount Amount of tokens to withdraw */ function withdraw(uint128 amount) external nonReentrant { require(lockedBalance[msg.sender] >= amount, "amount > unlocked balance"); lockedBalance[msg.sender] -= amount; token.transfer(msg.sender, amount); emit Withdraw(msg.sender, amount); } /** * @notice Allows slot owners to set a new slot delegate * @param slot Slot index * @param delegate Delegate address */ function setSlotDelegate(uint8 slot, address delegate) external onlySlotOwner(slot) { require(delegate != address(0), "cannot delegate to 0 address"); emit SlotDelegateUpdated(slot, msg.sender, delegate, slotDelegate(slot)); _slotDelegate[slot] = delegate; } /** * @notice Set new tax rate * @param numerator New tax numerator * @param denominator New tax denominator */ function setTaxRate(uint16 numerator, uint16 denominator) external onlyAdmin { require(denominator > numerator, "denominator must be > numerator"); emit TaxRateUpdated(numerator, denominator, taxNumerator, taxDenominator); taxNumerator = numerator; taxDenominator = denominator; } /** * @notice Set new admin * @param newAdmin Nex admin address */ function setAdmin(address newAdmin) external onlyAdmin { emit AdminUpdated(newAdmin, admin); admin = newAdmin; } /** * @notice Internal implementation of claimSlot * @param slot Slot index * @param bid Bid amount * @param delegate Delegate address */ function _claimSlot(uint8 slot, uint128 bid, address delegate) internal { require(delegate != address(0), "cannot delegate to 0 address"); Bid storage currentBid = slotBid[slot]; uint128 existingBidAmount = currentBid.bidAmount; uint128 existingSlotBalance = slotBalance(slot); uint128 taxedBalance = existingBidAmount - existingSlotBalance; require((existingSlotBalance == 0 && bid >= MIN_BID) || bid >= existingBidAmount * 110 / 100, "bid too small"); uint128 bidderLockedBalance = lockedBalance[msg.sender]; uint128 bidIncrement = currentBid.bidder == msg.sender ? bid - existingSlotBalance : bid; if (bidderLockedBalance > 0) { if (bidderLockedBalance >= bidIncrement) { lockedBalance[msg.sender] -= bidIncrement; } else { lockedBalance[msg.sender] = 0; token.transferFrom(msg.sender, address(this), bidIncrement - bidderLockedBalance); } } else { token.transferFrom(msg.sender, address(this), bidIncrement); } if (currentBid.bidder != msg.sender) { lockedBalance[currentBid.bidder] += existingSlotBalance; } if (taxedBalance > 0) { token.burn(taxedBalance); } _slotOwner[slot] = msg.sender; _slotDelegate[slot] = delegate; currentBid.bidder = msg.sender; currentBid.periodStart = uint64(block.timestamp); currentBid.bidAmount = bid; currentBid.taxNumerator = taxNumerator; currentBid.taxDenominator = taxDenominator; slotExpiration[slot] = uint64(block.timestamp + uint256(taxDenominator) * 86400 / uint256(taxNumerator)); emit SlotClaimed(slot, msg.sender, delegate, bid, existingBidAmount, taxNumerator, taxDenominator); } /** * @notice Internal implementation of stake * @param amount Amount of tokens to stake */ function _stake(uint128 amount) internal { token.transferFrom(msg.sender, address(this), amount); lockManager.grantVotingPower(msg.sender, address(token), amount); stakedBalance[msg.sender] += amount; emit Stake(msg.sender, amount); } }
Set new tax rate numerator New tax numerator denominator New tax denominator/
function setTaxRate(uint16 numerator, uint16 denominator) external onlyAdmin { require(denominator > numerator, "denominator must be > numerator"); emit TaxRateUpdated(numerator, denominator, taxNumerator, taxDenominator); taxNumerator = numerator; taxDenominator = denominator; }
12,801,181
// SPDX-License-Identifier: MIT pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; import "https://github.com/vigilance91/solidarity/contracts/accessControl/iAccessControl.sol"; import "https://github.com/vigilance91/solidarity/contracts/accessControl/AccessControlABC.sol"; /// /// @title Access Control /// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 19/4/2021, All Rights Reserved /// @dev role-based access control mechanisms, /// inspired by OpenZeppelin's AccessControl contract at: /// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/access/AccessControl.sol /// /// OpenZeppelin, respectfully, owns all rights to their original source in respects to its MIT license, however, /// Solidarity's version of AccessControl has been significantly rewritten from the ground up to not only increase readability but also /// reduces comment bloat, addes functionality, fixes some logic issues/potential bugs/invariants and reduce contract bytecode size /// /// Additionally, this version leverages encapsulation techniques pioneered by Solidarity, /// including the use of Constraints, Mixins, Protocols and Frameworks to extend usability, /// while still maintaining the neccessary core dependancies on OpenZeppelin, such as utils/Address and GSN/Context /// /// As such, in good spirits, this file maintains the original MIT license of OpenZeppelin's work from which it is inspired, /// the rest of the this package (which I personally wrote) is licensed under Apache-2.0 /// /// Vigilance does not claim any ownership of the original source material by OpenZepplin and acknowledges their exclusive rights, /// in respects to and as outlined by the MIT license. /// /// As such, this contract is published as free and open source software, as permitted by the MIT license. /// Vigilance does not profit from the use or distribution of this contract. /// /// Further modification to this software is permitted, /// only in respects to the original terms specified by the MIT license and must cite the original author, OpenZeppelin, /// as well as Vigilance and maintain the appropriate copyright notice and license. /// /// For more information please visit OpenZeppelin's documentation at: /// https://docs.openzeppelin.com/contracts/3.x/ /// /// NOTE: /// since Solidity does not allow embbeding comments in the compiled contract binaries. /// Due to this, in order to comply with the Apache-2.0 requirement to include the License with all binaries/executables, etc /// using EIP-926 (Global Meta-data Registry) and EIP-1753 (License Standard), /// it is possible to include/associate such license information on-chain with all contracts on the network which implement the Apache-2.0 License (or similar). /// However, there is no such requirement for the MIT license /// /// Roles are used to represent permissions and are repressented as `bytes32` identifiers and /// should be exposed in a derived contract's external API using `public constant` hash digests: /// ``` /// bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); /// ``` /// To restrict access to a function call, use {hasRole}: /// /// ``` /// function foo() public { /// require(hasRole(MY_ROLE, msg.sender)); /// ... /// } /// ``` /// OR as a modifier /// ``` /// function foo( /// )public requireRole( /// MY_ROLE, /// msg.sender /// ){ /// ... /// } /// ``` /// /// Each role has an associated admin which assigns or revokes roles dynamically via {grantRole} and {revokeRole} /// /// `DEFAULT_ADMIN_ROLE` is the default admin role for all roles, /// only addresses with this role are able to grant or revoke other roles /// /// WARNING: /// `DEFAULT_ADMIN_ROLE` is also its own admin thus, /// it has permission to grant and revoke this role /// Extra precautions should be taken to secure accounts that have been granted it, /// and is recommended that this role should only be assigned to a single address, /// potentilly either the contract deployer or owner (if ERC-173 compaliant) /// abstract contract AccessControl is AccessControlABC, //Context, iAccessControl { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; using eventsAccessControl for bytes32; using LogicConstraints for bool; using AddressConstraints for address; //using mixinAccessControl for address; //bytes32 private constant _STORAGE_SLOT = keccak256(); constructor( )internal //Context() AccessControlABC() { } /** modifier onlyRole( bytes32 role )internal { _requireHasRole(_msgSender(),role); _; } */ //helpful post-initialization, where it must be enforced 1 or more role members have been assigned a role /** function _requireRoleHasMembers( bytes32 role )public view override returns( uint256 ){ return _roleAt(role).members.length().requireGreaterThanZero(); } //helpful for initialization, where it must be enforced that no role members have been assigned function _requireRoleHasNoMembers( bytes32 role )public view override returns( uint256 ){ return _roleAt(role).members.length().requireEqualsZero(); } */ /** modifier onlyDefaultAdmin( )internal view { _requireRoleHasMembers(DEFAULT_ADMIN_ROLE); _requireIsDefaultAdmin(_msgSender()); _; } //modifier onlyDefaultAdminOrRoleAdmin( //)internal view //{ // //_; //} modifier onlyRole( bytes32 role )internal view { //_requireRoleHasMembers(role); _requireHasRole(role, _msgSender()); _; } modifier _requireNotHasRole( bytes32 role ){ _requireNotHasRole(role, _msgSender()); } modifier onlyRoleAdmin( bytes32 role ){ _requireHasAdminRole(role, _msgSender()); _; } modifier requireIsNotRoleAdmin( bytes32 role )internal view { _requireNotHasAdminRole(role, _msgSender()); _; } */ /// ///read-only interface /// /// @return {bool} `true` if `account` has been granted `role` /// /// Requirements: /// -account can not be zero address /// function hasRole( bytes32 role, address account )external view override returns( bool ){ //account.requireNotNull(); //return _roleAt(role).members.contains(account); return _hasRole(role, account); } /// /// @return {bool} `true` if `account` has been granted `role` /// /// Requirements: /// -account can not be zero address /// function hasRole( bytes32 role, address[] memory accounts )external view override returns( bool[] memory ){ return _hasRole(role, accounts); } /// /// @return {uint256} the number of accounts that have `role`, /// can be used together with {getRoleMember} to enumerate all bearers of a role /// function getRoleMemberCount( bytes32 role )public view override returns( uint256 ){ return _roleAt(role).members.length(); } /// /// @return {address} the account that have `role`, otherwise null /// `index` must be a value between 0 and {getRoleMemberCount}, non-inclusive /// /// NOTE: /// 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 /// /// for more information see: /// https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] /// function getRoleMember( bytes32 role, uint256 index )public view override returns( address ){ return _roleAt(role).members.at(index); } //function sliceRoleMembers( //bytes32 role, //uint256 start, //uint256 end //)public view override returns( //address //){ //return _roleAt(role).members.at(index); //} /// /// @return {bytes32} admin role that controls `role` /// See {grantRole} and {revokeRole} /// To change a role's admin, use {_setRoleAdmin} /// function getRoleAdmin( bytes32 role )public view override returns( bytes32 ){ return _roleAt(role).adminRole; } /// ///mutable interface /// /// /// @dev Grants `role` to `account` /// emits a {RoleGranted} event /// /// Requirements: /// - the caller must have ``role``'s admin role /// - reverts if `account` has previously been granted `role` /// function grantRole( bytes32 role, address account )public virtual override //onlyDefaultAdminOrRoleAdmin { _requireHasAdminRole(role, _msgSender()); _grantRole(role, account); } /// /// @dev Grants `role` to each account in `accounts` /// emits multiple {RoleGranted} event /// /// Requirements: /// - the caller must have `role`'s admin role or be default admin /// - reverts if an account in `account` has previously been granted `role` /// function grantRole( bytes32 role, address[] memory accounts )public virtual override //onlyDefaultAdminOrRoleAdmin { _requireHasAdminRole(role, _msgSender()); for(uint i; i < accounts.length; i++){ _grantRole(role, accounts[i]); } } /// /// @dev Revokes `role` from `account` /// emits a {RoleRevoked} event /// /// Requirements: /// - the caller must have ``role``'s admin role /// - reverts if `account` has not previously been granted `role` /// function revokeRole( bytes32 role, address account )public virtual override { _requireHasAdminRole(role, _msgSender()); _revokeRole(role, account); } /// /// @dev Revokes `role` from `account` /// emits a {RoleRevoked} event /// /// Requirements: /// - the caller must have ``role``'s admin role /// - reverts if `account` has not previously been granted `role` /// function revokeRole( bytes32 role, address[] memory accounts )public virtual override { _requireHasAdminRole(role, _msgSender()); for(uint i; i < accounts.length; i++){ _revokeRole(role, accounts[i]); } } /// /// @dev Revokes `role` from the calling account /// Roles are often managed via {grantRole} and {revokeRole}, /// this function's provides a mechanism for accounts to lose their privileges /// if they are compromised (such as when a trusted device is misplaced) /// Emits a {RoleRevoked} event /// /// Requirements: /// - the caller must be `account` /// - caller must have been previously granted Role, otherwise revert /// function renounceRole( bytes32 role //address account )public virtual override { //account.requireEqual( //_msgSender() //"can only renounce roles for self" //); _revokeRole(role, _msgSender()); } /// /// @dev Admin forces transfer of `role` from address `from` to address `to` /// emits a {RoleRevoked} even for `from` and {RoleGranted} event for `to` /// /// Requirements: /// - the caller must have `role`'s admin role or be default admin /// - `from` must not be null and currently have the role `role` /// - `to` must not be null and not have been assigned the role `role` /// /// NOTE: /// Be careful, default admin role can be transfered (only with the privallegaes it provides), /// this is useful along with transfering ownership via ERC173 /// however, if default admin role is transfered, this will immediately prevent any further admin operations, /// thus it should be the last role transfered, if at all /// function transferRole( bytes32 role, address from, address to )public virtual override //onlyDefaultAdminOrRoleAdmin { _requireHasAdminRole(role, _msgSender()); _transferRole(role, from, to); } }
helpful for initialization, where it must be enforced that no role members have been assigned
function _requireRoleHasNoMembers( bytes32 role )public view override returns( uint256 ){ return _roleAt(role).members.length().requireEqualsZero(); } )internal view
2,478,981
./full_match/1/0x519AE2616E0D87dBC05c2C00757894F883cDD5d6/sources/browser/BalavaDefiPool.sol
Deposit amount of ETH to contract with referral Should call this function one-time only when user deposit ETH the first time with referral address After that, user should send ETH direct to this contract address to deposit ETH to save gas. Deposit amount of Token to contract with referral If no referral address, juts set it to address(0) User MUST call approve function in Token contract to approve _value for this contract
function deposit(address payable _referral, uint256 _pool, uint256 _value) public payable { if (_pool == 0) { _deposit(msg.sender, 0, msg.value); TransferHelper.safeTransferETH(admin, msg.value); emit Deposit(msg.sender, _pool, _referral, msg.value); _deposit(msg.sender, _pool, _value); TransferHelper.safeTransferFrom(pools[_pool].token, msg.sender, address(this), _value); TransferHelper.safeTransfer(pools[_pool].token, admin, _value); emit Deposit(msg.sender, _pool, _referral, _value); } }
5,010,836
./full_match/42220/0xD3b0E4928D4c8Ba7c3037d7F05E56DF8CC78b450/sources/out/ProtocolFeePercentagesProvider_flat.sol
Interface for the SignatureValidator helper, used to support meta-transactions./
interface ISignaturesValidator { function getDomainSeparator() external view returns (bytes32); function getNextNonce(address user) external view returns (uint256); }
16,349,407
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // Welcome To BDT Airdrop // // send at least 0.0001 ETH to Smart Contract 0x97A4C01894F4B727979f6Ea86924E13C9fe2E619 // NOTE: do not forget to set the gas price 120,000 for the transaction to run smoothly //EXCHANGE: //while for the exchange, we have contacted some exchanges and we will probably be scheduled in the stock 4 days after the first stage 1 airdrop is done, this is the list of exchanges we managed to contact //1. Mercatox (negotiation) //2. idax (negotiation) //3. forkdelta (no response yet) //4. crex24 (negotiation) //5. bitebtc (negotiation) //6. idex (no response) //7. coinex (negotiation) //8. hitbtc (unconfirmed) //YOUR SUPPORT: //we appreciate your support, we are very excited and excited for all your support, // //supportive wallet: //-myetherwallet (online) //-metamask (extension) //-imtoken (Android) //-coinomi (Android) // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // 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); } // ---------------------------------------------------------------------------- // 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; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- 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); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Bitdepositary is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public bonusEnds; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Bitdepositary() public { symbol = "BDT"; name = "Bitdepositary"; decimals = 18; bonusEnds = now + 1500 weeks; endDate = now + 7500 weeks; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant 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] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // 1,000 FWD Tokens per 1 ETH // ------------------------------------------------------------------------ function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 500000001; } else { tokens = msg.value * 14000000000000000000000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // 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); } }
------------------------------------------------------------------------ 1,000 FWD Tokens per 1 ETH ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 500000001; tokens = msg.value * 14000000000000000000000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); }
14,012,116
./full_match/1/0x074895060e319f78e93688629d8497c58542733F/sources/contracts/FlyzLOOKSCapacitorV3.sol
Remove `depositor` from the list of addresses allowed to call `deposit()`/
function removeDepositor(address depositor) external onlyOwner { require(_depositors[depositor], "Capacitor: not depositor"); _depositors[depositor] = false; emit DepositorRemoved(depositor); }
5,007,195
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface iuniswap2 { //inject NONSTANDARD NAMING // To convert DAI to ETH function SWAPEXACTTOKENSFORETH53(uint AMOUNTIN88, uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING // To convert ETH to YELD and burn it function SWAPEXACTETHFORTOKENS6(uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external payable returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING } interface ierc2093 { //inject NONSTANDARD NAMING function TOTALSUPPLY70() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF25(address ACCOUNT45) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE65(address OWNER26, address SPENDER52) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE3(address SPENDER52, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER22(address indexed FROM88, address indexed TO76, uint256 VALUE83); //inject NONSTANDARD NAMING event APPROVAL93(address indexed OWNER26, address indexed SPENDER52, uint256 VALUE83); //inject NONSTANDARD NAMING } contract context61 { //inject NONSTANDARD NAMING constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER82() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA79() 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 ownable93 is context61 { //inject NONSTANDARD NAMING address payable private _OWNER43; //inject NONSTANDARD NAMING event OWNERSHIPTRANSFERRED63(address indexed PREVIOUSOWNER24, address indexed NEWOWNER52); //inject NONSTANDARD NAMING constructor () internal { _OWNER43 = _MSGSENDER82(); emit OWNERSHIPTRANSFERRED63(address(0), _OWNER43); } function OWNER99() public view returns (address payable) { //inject NONSTANDARD NAMING return _OWNER43; } modifier ONLYOWNER61() { //inject NONSTANDARD NAMING require(ISOWNER2(), "Ownable: caller is not the owner"); _; } function ISOWNER2() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER82() == _OWNER43; } function RENOUNCEOWNERSHIP13() public ONLYOWNER61 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED63(_OWNER43, address(0)); _OWNER43 = address(0); } function TRANSFEROWNERSHIP7(address payable NEWOWNER52) public ONLYOWNER61 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP60(NEWOWNER52); } function _TRANSFEROWNERSHIP60(address payable NEWOWNER52) internal { //inject NONSTANDARD NAMING require(NEWOWNER52 != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED63(_OWNER43, NEWOWNER52); _OWNER43 = NEWOWNER52; } } contract erc2030 is context61, ierc2093 { //inject NONSTANDARD NAMING using safemath13 for uint256; mapping (address => uint256) _BALANCES15; //inject NONSTANDARD NAMING mapping (address => mapping (address => uint256)) private _ALLOWANCES69; //inject NONSTANDARD NAMING uint256 _TOTALSUPPLY32; //inject NONSTANDARD NAMING function TOTALSUPPLY70() public view returns (uint256) { //inject NONSTANDARD NAMING return _TOTALSUPPLY32; } function BALANCEOF25(address ACCOUNT45) public view returns (uint256) { //inject NONSTANDARD NAMING return _BALANCES15[ACCOUNT45]; } function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(_MSGSENDER82(), RECIPIENT39, AMOUNT4); return true; } function ALLOWANCE65(address OWNER26, address SPENDER52) public view returns (uint256) { //inject NONSTANDARD NAMING return _ALLOWANCES69[OWNER26][SPENDER52]; } function APPROVE3(address SPENDER52, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, AMOUNT4); return true; } function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(SENDER75, RECIPIENT39, AMOUNT4); _APPROVE30(SENDER75, _MSGSENDER82(), _ALLOWANCES69[SENDER75][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE47(address SPENDER52, uint256 ADDEDVALUE76) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].ADD27(ADDEDVALUE76)); return true; } function DECREASEALLOWANCE20(address SPENDER52, uint256 SUBTRACTEDVALUE75) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].SUB57(SUBTRACTEDVALUE75, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER95(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(SENDER75 != address(0), "ERC20: transfer from the zero address"); require(RECIPIENT39 != address(0), "ERC20: transfer to the zero address"); _BALANCES15[SENDER75] = _BALANCES15[SENDER75].SUB57(AMOUNT4, "ERC20: transfer amount exceeds balance"); _BALANCES15[RECIPIENT39] = _BALANCES15[RECIPIENT39].ADD27(AMOUNT4); emit TRANSFER22(SENDER75, RECIPIENT39, AMOUNT4); } function _MINT79(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: mint to the zero address"); _TOTALSUPPLY32 = _TOTALSUPPLY32.ADD27(AMOUNT4); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].ADD27(AMOUNT4); emit TRANSFER22(address(0), ACCOUNT45, AMOUNT4); } function _BURN68(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: burn from the zero address"); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].SUB57(AMOUNT4, "ERC20: burn amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(AMOUNT4); emit TRANSFER22(ACCOUNT45, address(0), AMOUNT4); } function _APPROVE30(address OWNER26, address SPENDER52, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(OWNER26 != address(0), "ERC20: approve from the zero address"); require(SPENDER52 != address(0), "ERC20: approve to the zero address"); _ALLOWANCES69[OWNER26][SPENDER52] = AMOUNT4; emit APPROVAL93(OWNER26, SPENDER52, AMOUNT4); } function _BURNFROM66(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING _BURN68(ACCOUNT45, AMOUNT4); _APPROVE30(ACCOUNT45, _MSGSENDER82(), _ALLOWANCES69[ACCOUNT45][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: burn amount exceeds allowance")); } } contract erc20detailed21 is ierc2093 { //inject NONSTANDARD NAMING string private _NAME42; //inject NONSTANDARD NAMING string private _SYMBOL85; //inject NONSTANDARD NAMING uint8 private _DECIMALS78; //inject NONSTANDARD NAMING constructor (string memory NAME99, string memory SYMBOL38, uint8 DECIMALS96) public { //inject NONSTANDARD NAMING _NAME42 = NAME99; _SYMBOL85 = SYMBOL38; _DECIMALS78 = DECIMALS96; } function NAME45() public view returns (string memory) { //inject NONSTANDARD NAMING return _NAME42; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _SYMBOL85; } function DECIMALS63() public view returns (uint8) { //inject NONSTANDARD NAMING return _DECIMALS78; } } contract reentrancyguard94 { //inject NONSTANDARD NAMING uint256 private _GUARDCOUNTER38; //inject NONSTANDARD NAMING constructor () internal { _GUARDCOUNTER38 = 1; } modifier NONREENTRANT47() { //inject NONSTANDARD NAMING _GUARDCOUNTER38 += 1; uint256 LOCALCOUNTER54 = _GUARDCOUNTER38; //inject NONSTANDARD NAMING _; require(LOCALCOUNTER54 == _GUARDCOUNTER38, "ReentrancyGuard: reentrant call"); } } library safemath13 { //inject NONSTANDARD NAMING function ADD27(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 C51 = A32 + B30; //inject NONSTANDARD NAMING require(C51 >= A32, "SafeMath: addition overflow"); return C51; } function SUB57(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB57(A32, B30, "SafeMath: subtraction overflow"); } function SUB57(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 <= A32, ERRORMESSAGE15); uint256 C51 = A32 - B30; //inject NONSTANDARD NAMING return C51; } function MUL24(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (A32 == 0) { return 0; } uint256 C51 = A32 * B30; //inject NONSTANDARD NAMING require(C51 / A32 == B30, "SafeMath: multiplication overflow"); return C51; } function DIV26(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV26(A32, B30, "SafeMath: division by zero"); } function DIV26(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(B30 > 0, ERRORMESSAGE15); uint256 C51 = A32 / B30; //inject NONSTANDARD NAMING return C51; } function MOD76(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD76(A32, B30, "SafeMath: modulo by zero"); } function MOD76(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 != 0, ERRORMESSAGE15); return A32 % B30; } } library address92 { //inject NONSTANDARD NAMING function ISCONTRACT77(address ACCOUNT45) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 CODEHASH48; //inject NONSTANDARD NAMING bytes32 ACCOUNTHASH81 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING // solhint-disable-next-line no-inline-assembly assembly { CODEHASH48 := extcodehash(ACCOUNT45) } return (CODEHASH48 != 0x0 && CODEHASH48 != ACCOUNTHASH81); } function TOPAYABLE47(address ACCOUNT45) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(ACCOUNT45)); } function SENDVALUE65(address payable RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(address(this).balance >= AMOUNT4, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool SUCCESS17, ) = RECIPIENT39.call.value(AMOUNT4)(""); //inject NONSTANDARD NAMING require(SUCCESS17, "Address: unable to send value, recipient may have reverted"); } } library safeerc2059 { //inject NONSTANDARD NAMING using safemath13 for uint256; using address92 for address; function SAFETRANSFER30(ierc2093 TOKEN25, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFER37.selector, TO76, VALUE83)); } function SAFETRANSFERFROM76(ierc2093 TOKEN25, address FROM88, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFERFROM19.selector, FROM88, TO76, VALUE83)); } function SAFEAPPROVE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING require((VALUE83 == 0) || (TOKEN25.ALLOWANCE65(address(this), SPENDER52) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, VALUE83)); } function SAFEINCREASEALLOWANCE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).ADD27(VALUE83); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function SAFEDECREASEALLOWANCE48(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).SUB57(VALUE83, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function CALLOPTIONALRETURN90(ierc2093 TOKEN25, bytes memory DATA85) private { //inject NONSTANDARD NAMING require(address(TOKEN25).ISCONTRACT77(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool SUCCESS17, bytes memory RETURNDATA42) = address(TOKEN25).call(DATA85); //inject NONSTANDARD NAMING require(SUCCESS17, "SafeERC20: low-level call failed"); if (RETURNDATA42.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(RETURNDATA42, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface compound17 { //inject NONSTANDARD NAMING function MINT37 ( uint256 MINTAMOUNT46 ) external returns ( uint256 ); //inject NONSTANDARD NAMING function REDEEM71(uint256 REDEEMTOKENS65) external returns (uint256); //inject NONSTANDARD NAMING function EXCHANGERATESTORED22() external view returns (uint); //inject NONSTANDARD NAMING } interface fulcrum27 { //inject NONSTANDARD NAMING function MINT37(address RECEIVER66, uint256 AMOUNT4) external payable returns (uint256 MINTAMOUNT46); //inject NONSTANDARD NAMING function BURN1(address RECEIVER66, uint256 BURNAMOUNT5) external returns (uint256 LOANAMOUNTPAID4); //inject NONSTANDARD NAMING function ASSETBALANCEOF38(address _OWNER43) external view returns (uint256 BALANCE2); //inject NONSTANDARD NAMING } interface ilendingpooladdressesprovider93 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING } interface aave60 { //inject NONSTANDARD NAMING function DEPOSIT43(address _RESERVE54, uint256 _AMOUNT50, uint16 _REFERRALCODE69) external; //inject NONSTANDARD NAMING } interface atoken49 { //inject NONSTANDARD NAMING function REDEEM71(uint256 AMOUNT4) external; //inject NONSTANDARD NAMING } interface iiearnmanager83 { //inject NONSTANDARD NAMING function RECOMMEND99(address _TOKEN3) external view returns ( //inject NONSTANDARD NAMING string memory CHOICE41, //inject NONSTANDARD NAMING uint256 CAPR5, //inject NONSTANDARD NAMING uint256 IAPR100, //inject NONSTANDARD NAMING uint256 AAPR96, //inject NONSTANDARD NAMING uint256 DAPR97 //inject NONSTANDARD NAMING ); } contract structs50 { //inject NONSTANDARD NAMING struct Val { uint256 VALUE83; //inject NONSTANDARD NAMING } enum ActionType { Deposit, // supply tokens Withdraw // borrow tokens } enum AssetDenomination { Wei // the amount is denominated in wei } enum AssetReference { Delta // the amount is given as a delta from the current value } struct AssetAmount { bool SIGN32; // true if positive //inject NONSTANDARD NAMING AssetDenomination DENOMINATION0; //inject NONSTANDARD NAMING AssetReference REF97; //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } struct ActionArgs { ActionType ACTIONTYPE60; //inject NONSTANDARD NAMING uint256 ACCOUNTID6; //inject NONSTANDARD NAMING AssetAmount AMOUNT4; //inject NONSTANDARD NAMING uint256 PRIMARYMARKETID93; //inject NONSTANDARD NAMING uint256 SECONDARYMARKETID1; //inject NONSTANDARD NAMING address OTHERADDRESS81; //inject NONSTANDARD NAMING uint256 OTHERACCOUNTID93; //inject NONSTANDARD NAMING bytes DATA85; //inject NONSTANDARD NAMING } struct Info { address OWNER26; // The address that owns the account //inject NONSTANDARD NAMING uint256 NUMBER25; // A nonce that allows a single address to control many accounts //inject NONSTANDARD NAMING } struct Wei { bool SIGN32; // true if positive //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } } contract dydx100 is structs50 { //inject NONSTANDARD NAMING function GETACCOUNTWEI65(Info memory ACCOUNT45, uint256 MARKETID4) public view returns (Wei memory); //inject NONSTANDARD NAMING function OPERATE53(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING } interface lendingpooladdressesprovider85 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE37() external view returns (address); //inject NONSTANDARD NAMING } contract yusdc19 is erc2030, erc20detailed21, reentrancyguard94, structs50, ownable93 { //inject NONSTANDARD NAMING using safeerc2059 for ierc2093; using address92 for address; using safemath13 for uint256; struct Deposit { uint256 AMOUNT4; //inject NONSTANDARD NAMING uint256 START33; // Block when it started //inject NONSTANDARD NAMING } uint256 public POOL37; //inject NONSTANDARD NAMING address public TOKEN25; //inject NONSTANDARD NAMING address public COMPOUND53; //inject NONSTANDARD NAMING address public FULCRUM19; //inject NONSTANDARD NAMING address public AAVE10; //inject NONSTANDARD NAMING address public AAVEPOOL17; //inject NONSTANDARD NAMING address public AAVETOKEN8; //inject NONSTANDARD NAMING address public DYDX62; //inject NONSTANDARD NAMING uint256 public DTOKEN6; //inject NONSTANDARD NAMING address public APR50; //inject NONSTANDARD NAMING address public CHAI29; //inject NONSTANDARD NAMING // Add other tokens if implemented for another stablecoin address public UNISWAPROUTER94 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //inject NONSTANDARD NAMING address public USDC51 = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; //inject NONSTANDARD NAMING address public WETH0 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING address payable public RETIREMENTYELDTREASURY39; //inject NONSTANDARD NAMING ierc2093 public YELDTOKEN43; //inject NONSTANDARD NAMING uint256 public MAXIMUMTOKENSTOBURN49 = 50000 * 1e18; //inject NONSTANDARD NAMING uint256 public constant minimumeffectamount5 = 5 * 10 ** 18; //inject NONSTANDARD NAMING // When you stake say 1000 USDC for a day that will be your maximum // if you stake the next time 300 USDC your maximum will stay the same // if you stake 2000 at once it will increase to 2000 USDC mapping(bytes32 => uint256) public NUMBEROFPARTICIPANTS77; //inject NONSTANDARD NAMING mapping(address => Deposit) public DEPOSITS12; //inject NONSTANDARD NAMING uint256 public constant onedayinblocks19 = 6500; //inject NONSTANDARD NAMING uint256 public YELDTOREWARDPERDAY12 = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility //inject NONSTANDARD NAMING uint256 public constant onemillion14 = 1e6; //inject NONSTANDARD NAMING enum Lender { NONE, DYDX, COMPOUND, AAVE, FULCRUM } Lender public PROVIDER42 = Lender.NONE; //inject NONSTANDARD NAMING constructor (address _YELDTOKEN72, address payable _RETIREMENTYELDTREASURY14) public payable erc20detailed21("yearn USDC", "yUSDC", 18) { //inject NONSTANDARD NAMING TOKEN25 = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); APR50 = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8); DYDX62 = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); AAVE10 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); AAVEPOOL17 = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3); FULCRUM19 = address(0x493C57C4763932315A328269E1ADaD09653B9081); AAVETOKEN8 = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); COMPOUND53 = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); CHAI29 = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); DTOKEN6 = 3; YELDTOKEN43 = ierc2093(_YELDTOKEN72); RETIREMENTYELDTREASURY39 = _RETIREMENTYELDTREASURY14; APPROVETOKEN12(); } // To receive ETH after converting it from USDC function () external payable {} function SETRETIREMENTYELDTREASURY49(address payable _TREASURY6) public ONLYOWNER61 { //inject NONSTANDARD NAMING RETIREMENTYELDTREASURY39 = _TREASURY6; } // In case a new uniswap router version is released function SETUNISWAPROUTER20(address _UNISWAPROUTER42) public ONLYOWNER61 { //inject NONSTANDARD NAMING UNISWAPROUTER94 = _UNISWAPROUTER42; } function EXTRACTTOKENSIFSTUCK53(address _TOKEN3, uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING ierc2093(_TOKEN3).TRANSFER37(msg.sender, _AMOUNT50); } function EXTRACTETHIFSTUCK0() public ONLYOWNER61 { //inject NONSTANDARD NAMING OWNER99().transfer(address(this).balance); } function CHANGEYELDTOREWARDPERDAY13(uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING YELDTOREWARDPERDAY12 = _AMOUNT50; } function GETGENERATEDYELDS73() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 BLOCKSPASSED1; //inject NONSTANDARD NAMING if (DEPOSITS12[msg.sender].START33 > 0) { BLOCKSPASSED1 = block.number.SUB57(DEPOSITS12[msg.sender].START33); } else { BLOCKSPASSED1 = 0; } // This will work because amount is a token with 18 decimals // Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1 // That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day // your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since // we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding uint256 GENERATEDYELDS87 = DEPOSITS12[msg.sender].AMOUNT4.DIV26(onemillion14).MUL24(YELDTOREWARDPERDAY12.DIV26(1e18)).MUL24(BLOCKSPASSED1).DIV26(onedayinblocks19); //inject NONSTANDARD NAMING return GENERATEDYELDS87; } function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99() public { //inject NONSTANDARD NAMING require(DEPOSITS12[msg.sender].START33 > 0 && DEPOSITS12[msg.sender].AMOUNT4 > 0, 'Must have deposited stablecoins beforehand'); uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4, block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); } function DEPOSIT43(uint256 _AMOUNT50) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_AMOUNT50 > 0, "deposit must be greater than 0"); POOL37 = CALCPOOLVALUEINTOKEN17(); ierc2093(TOKEN25).SAFETRANSFERFROM76(msg.sender, address(this), _AMOUNT50); // Yeld if (GETGENERATEDYELDS73() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99(); DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.ADD27(_AMOUNT50), block.number); // Yeld // Calculate pool shares uint256 SHARES22 = 0; //inject NONSTANDARD NAMING if (POOL37 == 0) { SHARES22 = _AMOUNT50; POOL37 = _AMOUNT50; } else { SHARES22 = (_AMOUNT50.MUL24(_TOTALSUPPLY32)).DIV26(POOL37); } POOL37 = CALCPOOLVALUEINTOKEN17(); _MINT79(msg.sender, SHARES22); } // Converts USDC to ETH and returns how much ETH has been received from Uniswap function USDCTOETH25(uint256 _AMOUNT50) internal returns(uint256) { //inject NONSTANDARD NAMING ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, 0); ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, _AMOUNT50); address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = USDC51; PATH78[1] = WETH0; // swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) // 'amounts' is an array where [0] is input USDC amount and [1] is the resulting ETH after the conversion // even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap // https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTTOKENSFORETH53(_AMOUNT50, uint(0), PATH78, address(this), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // Buys YELD tokens paying in ETH on Uniswap and removes them from circulation // Returns how many YELD tokens have been burned function BUYNBURN98(uint256 _ETHTOSWAP66) internal returns(uint256) { //inject NONSTANDARD NAMING address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = WETH0; PATH78[1] = address(YELDTOKEN43); // Burns the tokens by taking them out of circulation, sending them to the 0x0 address uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTETHFORTOKENS6.value(_ETHTOSWAP66)(uint(0), PATH78, address(0), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // No rebalance implementation for lower fees and faster swaps function WITHDRAW27(uint256 _SHARES43) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_SHARES43 > 0, "withdraw must be greater than 0"); uint256 IBALANCE43 = BALANCEOF25(msg.sender); //inject NONSTANDARD NAMING require(_SHARES43 <= IBALANCE43, "insufficient balance"); POOL37 = CALCPOOLVALUEINTOKEN17(); uint256 R82 = (POOL37.MUL24(_SHARES43)).DIV26(_TOTALSUPPLY32); //inject NONSTANDARD NAMING _BALANCES15[msg.sender] = _BALANCES15[msg.sender].SUB57(_SHARES43, "redeem amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(_SHARES43); emit TRANSFER22(msg.sender, address(0), _SHARES43); uint256 B30 = ierc2093(TOKEN25).BALANCEOF25(address(this)); //inject NONSTANDARD NAMING if (B30 < R82) { _WITHDRAWSOME38(R82.SUB57(B30)); } // Yeld uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING uint256 HALFPROFITS96 = (R82.SUB57(DEPOSITS12[msg.sender].AMOUNT4, '#3 Half profits sub error')).DIV26(2); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.SUB57(_SHARES43), block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); // Take a portion of the profits for the buy and burn and retirement yeld // Convert half the USDC earned into ETH for the protocol algorithms if (HALFPROFITS96 > minimumeffectamount5) { uint256 STAKINGPROFITS48 = USDCTOETH25(HALFPROFITS96); //inject NONSTANDARD NAMING uint256 TOKENSALREADYBURNED29 = YELDTOKEN43.BALANCEOF25(address(0)); //inject NONSTANDARD NAMING if (TOKENSALREADYBURNED29 < MAXIMUMTOKENSTOBURN49) { // 98% is the 49% doubled since we already took the 50% uint256 ETHTOSWAP53 = STAKINGPROFITS48.MUL24(98).DIV26(100); //inject NONSTANDARD NAMING // Buy and burn only applies up to 50k tokens burned BUYNBURN98(ETHTOSWAP53); // 1% for the Retirement Yield uint256 RETIREMENTYELD83 = STAKINGPROFITS48.MUL24(2).DIV26(100); //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } else { // If we've reached the maximum burn point, send half the profits to the treasury to reward holders uint256 RETIREMENTYELD83 = STAKINGPROFITS48; //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } } // Yeld ierc2093(TOKEN25).SAFETRANSFER30(msg.sender, R82); POOL37 = CALCPOOLVALUEINTOKEN17(); } function RECOMMEND99() public view returns (Lender) { //inject NONSTANDARD NAMING (,uint256 CAPR5,uint256 IAPR100,uint256 AAPR96,uint256 DAPR97) = iiearnmanager83(APR50).RECOMMEND99(TOKEN25); //inject NONSTANDARD NAMING uint256 MAX28 = 0; //inject NONSTANDARD NAMING if (CAPR5 > MAX28) { MAX28 = CAPR5; } if (IAPR100 > MAX28) { MAX28 = IAPR100; } if (AAPR96 > MAX28) { MAX28 = AAPR96; } if (DAPR97 > MAX28) { MAX28 = DAPR97; } Lender NEWPROVIDER38 = Lender.NONE; //inject NONSTANDARD NAMING if (MAX28 == CAPR5) { NEWPROVIDER38 = Lender.COMPOUND; } else if (MAX28 == IAPR100) { NEWPROVIDER38 = Lender.FULCRUM; } else if (MAX28 == AAPR96) { NEWPROVIDER38 = Lender.AAVE; } else if (MAX28 == DAPR97) { NEWPROVIDER38 = Lender.DYDX; } return NEWPROVIDER38; } function GETAAVE86() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOL88(); } function GETAAVECORE62() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOLCORE37(); } function APPROVETOKEN12() public { //inject NONSTANDARD NAMING ierc2093(TOKEN25).SAFEAPPROVE32(COMPOUND53, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(DYDX62, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(GETAAVECORE62(), uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(FULCRUM19, uint(-1)); } function BALANCE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(address(this)); } function BALANCEDYDXAVAILABLE58() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(DYDX62); } function BALANCEDYDX47() public view returns (uint256) { //inject NONSTANDARD NAMING Wei memory BAL85 = dydx100(DYDX62).GETACCOUNTWEI65(Info(address(this), 0), DTOKEN6); //inject NONSTANDARD NAMING return BAL85.VALUE83; } function BALANCECOMPOUND27() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(COMPOUND53).BALANCEOF25(address(this)); } function BALANCECOMPOUNDINTOKEN38() public view returns (uint256) { //inject NONSTANDARD NAMING // Mantisa 1e18 to decimals uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = B30.MUL24(compound17(COMPOUND53).EXCHANGERATESTORED22()).DIV26(1e18); } return B30; } function BALANCEFULCRUMAVAILABLE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(CHAI29).BALANCEOF25(FULCRUM19); } function BALANCEFULCRUMINTOKEN93() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = fulcrum27(FULCRUM19).ASSETBALANCEOF38(address(this)); } return B30; } function BALANCEFULCRUM60() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(FULCRUM19).BALANCEOF25(address(this)); } function BALANCEAAVEAVAILABLE0() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(AAVEPOOL17); } function BALANCEAAVE23() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(AAVETOKEN8).BALANCEOF25(address(this)); } function REBALANCE91() public { //inject NONSTANDARD NAMING Lender NEWPROVIDER38 = RECOMMEND99(); //inject NONSTANDARD NAMING if (NEWPROVIDER38 != PROVIDER42) { _WITHDRAWALL34(); } if (BALANCE62() > 0) { if (NEWPROVIDER38 == Lender.DYDX) { _SUPPLYDYDX52(BALANCE62()); } else if (NEWPROVIDER38 == Lender.FULCRUM) { _SUPPLYFULCRUM48(BALANCE62()); } else if (NEWPROVIDER38 == Lender.COMPOUND) { _SUPPLYCOMPOUND47(BALANCE62()); } else if (NEWPROVIDER38 == Lender.AAVE) { _SUPPLYAAVE98(BALANCE62()); } } PROVIDER42 = NEWPROVIDER38; } function _WITHDRAWALL34() internal { //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEDYDXAVAILABLE58()) { AMOUNT4 = BALANCEDYDXAVAILABLE58(); } _WITHDRAWDYDX0(AMOUNT4); } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); } _WITHDRAWSOMEFULCRUM68(AMOUNT4); } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEAAVEAVAILABLE0()) { AMOUNT4 = BALANCEAAVEAVAILABLE0(); } _WITHDRAWAAVE10(AMOUNT4); } } function _WITHDRAWSOMECOMPOUND30(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCECOMPOUNDINTOKEN38(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWCOMPOUND82(AMOUNT4); } function _WITHDRAWSOMEFULCRUM68(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCEFULCRUMINTOKEN93(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWFULCRUM65(AMOUNT4); } function _WITHDRAWSOME38(uint256 _AMOUNT50) internal returns (bool) { //inject NONSTANDARD NAMING uint256 ORIGAMOUNT32 = _AMOUNT50; //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCECOMPOUNDINTOKEN38().SUB57(1)) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMECOMPOUND30(_AMOUNT50); return true; } } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEDYDXAVAILABLE58()) { _WITHDRAWDYDX0(BALANCEDYDXAVAILABLE58()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWDYDX0(_AMOUNT50); return true; } } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); _WITHDRAWSOMEFULCRUM68(BALANCEFULCRUMAVAILABLE62().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMEFULCRUM68(AMOUNT4); return true; } } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEAAVEAVAILABLE0()) { _WITHDRAWAAVE10(BALANCEAAVEAVAILABLE0()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWAAVE10(_AMOUNT50); return true; } } return true; } function _SUPPLYDYDX52(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Deposit; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function _SUPPLYAAVE98(uint AMOUNT4) internal { //inject NONSTANDARD NAMING aave60(GETAAVE86()).DEPOSIT43(TOKEN25, AMOUNT4, 0); } function _SUPPLYFULCRUM48(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).MINT37(address(this), AMOUNT4) > 0, "FULCRUM: supply failed"); } function _SUPPLYCOMPOUND47(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).MINT37(AMOUNT4) == 0, "COMPOUND: supply failed"); } function _WITHDRAWAAVE10(uint AMOUNT4) internal { //inject NONSTANDARD NAMING atoken49(AAVETOKEN8).REDEEM71(AMOUNT4); } function _WITHDRAWFULCRUM65(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).BURN1(address(this), AMOUNT4) > 0, "FULCRUM: withdraw failed"); } function _WITHDRAWCOMPOUND82(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).REDEEM71(AMOUNT4) == 0, "COMPOUND: withdraw failed"); } function _WITHDRAWDYDX0(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Withdraw; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function CALCPOOLVALUEINTOKEN17() public view returns (uint) { //inject NONSTANDARD NAMING return BALANCECOMPOUNDINTOKEN38() .ADD27(BALANCEFULCRUMINTOKEN93()) .ADD27(BALANCEDYDX47()) .ADD27(BALANCEAAVE23()) .ADD27(BALANCE62()); } function GETPRICEPERFULLSHARE16() public view returns (uint) { //inject NONSTANDARD NAMING uint _POOL79 = CALCPOOLVALUEINTOKEN17(); //inject NONSTANDARD NAMING return _POOL79.MUL24(1e18).DIV26(_TOTALSUPPLY32); } }
inject NONSTANDARD NAMING
function OWNER99() public view returns (address payable) {
7,220,329