file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/5/0x777d8d5d76b3abE983dE78bC6c2a526b62381f64/sources/NCore.flat.sol | WRITE METHODS/ List source token that will be swapped. _token Token address./ | function listSrcToken(address _token) external onlyOwner {
require(_token != address(0), "NPairs: Null address not allowed");
require(!srcToken[_token], "NPairs: Token already listed");
_listSrcToken(_token);
}
| 11,585,835 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./LookupTables.sol";
library Calculus {
struct fn { // fn will always mean "function"
Form form;
int scalar;
int[] coefficients;
fn[] operands;
BinaryOp op;
uint one;
} // TODO put a mechanism to restrict domain in the fn, see d/dx ln(x) = 1/x
uint constant PI = 3141592653589793238462643383279502884; // to 36 decimal places
enum Form {BINARYOP, POLYNOMIAL, SIN, COS, EXP, LN, CONSTANT} // etc
enum BinaryOp {NONE, COMPOSITION, ADD, SUBTRACT, MULTIPLY, DIVIDE}
// transcendental
function newFn(Form form, uint one) internal pure returns(fn memory) {
require(form > Form.POLYNOMIAL, "use newFn(int[]) for POLYNOMIAL");
fn[] memory blank;
int[] memory blank_;
return fn(form, 1, blank_, blank, BinaryOp.NONE, one);
}
function newFn(Form form, uint one, int scalar) internal pure returns(fn memory) {
require(form > Form.POLYNOMIAL, "use newFn(int[]) for POLYNOMIAL");
fn[] memory blank;
int[] memory blank_;
return fn(form, scalar, blank_, blank, BinaryOp.NONE, one);
}
// polynomial
function newFn(int[] memory coefficients, uint one) internal pure returns(fn memory) {
fn[] memory blank;
return fn(Form.POLYNOMIAL, 1, coefficients, blank, BinaryOp.NONE, one);
}
function newFn(int[] memory coefficients, int scalar, uint one) internal pure returns(fn memory) {
fn[] memory blank;
return fn(Form.POLYNOMIAL, scalar, coefficients, blank, BinaryOp.NONE, one);
}
// as operation
function newFn(fn[] memory operands, BinaryOp op) internal pure returns(fn memory) {
int[] memory blank_;
return fn(Form.BINARYOP, 0, blank_, operands, op, 0);
}
struct Number {
int value;
uint one;
}
function evaluate(fn memory self, int input, uint accuracy, uint[] memory factorialReciprocalsLookupTable) internal pure returns(Number memory) {
require(self.form != Form.CONSTANT, "cannot evaluate a constant form.");
if (self.form == Form.BINARYOP)
return _evaluateBinaryOperation(self, input, accuracy, factorialReciprocalsLookupTable);
if (self.form == Form.POLYNOMIAL)
return _evaluatePolynomial(self, input);
// else form == TRANSCENDENTAL
return _evaluateTranscendental(self, input, accuracy, factorialReciprocalsLookupTable);
}
// evaluates polynomial having rational input and coeffiecients
function evaluate(fn memory self, int input) internal pure returns(Number memory) { //returns(int) {
require(self.form == Form.POLYNOMIAL, "form must be polynomial.");
return _evaluatePolynomial(self, input);
}
enum QuotientType {NONE, FACTORIAL, FACTOR}
function _evaluateTranscendental(fn memory self, int input, uint accuracy, uint[] memory factorialReciprocalsLookupTable) private pure returns(Number memory) {
int[] memory coefficients = new int[](2*accuracy+1);
QuotientType qt = QuotientType.NONE;
uint startIdx;
uint idxGap=1;
int unit=1;
if (self.form < Form.EXP) { // then is sin or cos
qt = QuotientType.FACTORIAL;
input = _putInNeighborhoodOfZero(input, self.one);
accuracy = 2*accuracy;
startIdx = (self.form==Form.SIN) ? 1 : 0;
idxGap=2;
unit=-1;
} else if (self.form == Form.EXP) {
qt = QuotientType.FACTORIAL;
// it's really lovely the many ways EXP is composed with SIN,COS in both R, C :)
} else if (self.form == Form.LN) {
qt = QuotientType.FACTOR;
// the Maclaurin series we use is ln(1+x) so shift the input
input = input - int(self.one);
// the Maclaurin series we use is ln(1+x) but only converges for (-1,1]
require(-int(self.one) < input && input <=int(self.one), "input out of domain.");
// TODO make the domain check above instead branch to other methods of computing ln(x)...
accuracy = 2*accuracy;
startIdx = 1;
unit=-1;
}
uint[] memory lookupTable = factorialReciprocalsLookupTable;
if (qt == QuotientType.FACTOR) {
lookupTable = LookupTables.buildFactorReciprocalsLookupTable(accuracy);
} else { // qt == QuotientType.NONE
// TODO
}
{ // stack too deep
uint idx;
uint n;
if (startIdx==1) {
coefficients[idx]=0;
idx++;
}
for (uint i=startIdx; i<accuracy; i+=idxGap) {
coefficients[idx] = (unit**n) * int(lookupTable[i]) * int(self.one) / int(LookupTables.one);
n++;
idx+=idxGap;
}
}
return _evaluatePolynomial(newFn(coefficients, self.scalar, self.one), input);
}
function _putInNeighborhoodOfZero(int input, uint one) private pure returns(int ret) {
uint TwoPiNormalized = 2 * PI * one / (10**36);
ret = input % int(TwoPiNormalized); // we embrace the periodicity
}
// assumes input, and coefficients are rationals Q
function _evaluatePolynomial(fn memory self, int input) private pure returns(Number memory) {
uint coefLen = self.coefficients.length;
int lastPower = int(self.one);
int power;
int ret = self.coefficients[0] * lastPower;
for (uint i=1; i<coefLen; i++) {
power = lastPower * input / int(self.one);
ret += self.coefficients[i] * power;
lastPower = power;
}
ret = ret / int(self.one);
return Number(self.scalar * ret, self.one);
}
// TODO test correctness
function _evaluateBinaryOperation(fn memory self, int input, uint accuracy, uint[] memory factorialReciprocalsLookupTable) private pure returns(Number memory) {
require(self.op > BinaryOp.NONE && self.op <= BinaryOp.DIVIDE, "BinaryOp undefined.");
Number memory res1 = evaluate(self.operands[1], input, accuracy, factorialReciprocalsLookupTable);
if (self.op == BinaryOp.COMPOSITION) {
res1.value = res1.value * int(self.operands[0].one) / int(res1.one); // normalize
return evaluate(self.operands[0], res1.value, accuracy, factorialReciprocalsLookupTable);
}
Number memory res0 = evaluate(self.operands[0], input, accuracy, factorialReciprocalsLookupTable);
(res0, res1) = _normalizeWRTOnes(res0, res1);
if (self.op == BinaryOp.ADD) {
return Number(res0.value + res1.value, res0.one);
}
if (self.op == BinaryOp.SUBTRACT) {
return Number(res0.value - res1.value, res0.one);
}
if (self.op == BinaryOp.MULTIPLY) {
return Number(res0.value * res1.value / int(res0.one), res0.one);
} // else if fn.op == BinaryOp.DIVIDE
return Number(int(res0.one) * res0.value / res1.value, res0.one);
}
function _normalizeWRTOnes(Number memory n0, Number memory n1) private pure returns(Number memory, Number memory) {
if (n0.one==n1.one) return (n0, n1);
if (n0.one < n1.one)
return (Number(int(n1.one)*n0.value/int(n0.one), n1.one), n1);
return (n0, Number(int(n0.one)*n1.value/int(n1.one), n0.one));
}
function compose(fn memory self, fn memory other) internal pure returns(fn memory) {
fn[] memory operands = new fn[](2);
operands[0] = self;
operands[1] = other;
return newFn(operands, BinaryOp.COMPOSITION);
}
function differentiate(fn memory self) internal pure returns(fn memory) {
if (self.form == Form.CONSTANT) {
int[] memory coefficients = new int[](1); // 0
return newFn(coefficients, self.one); // f(x) = 0
}
if (self.form > Form.POLYNOMIAL)
return _differentiateTranscendental(self);
if (self.form == Form.POLYNOMIAL)
return _differentiatePolynomial(self);
return _differentiateBinaryOp(self);
}
function _differentiateTranscendental(fn memory self) private pure returns(fn memory) {
if (self.form == Form.SIN) {
return newFn(Form.COS, self.one, self.scalar);
} else if (self.form == Form.COS) {
return newFn(Form.SIN, self.one, -self.scalar);
} else if (self.form == Form.LN) {
// this should add a restriction to the domain...
// TODO put a mechanism to restrict domain in the fn
fn[] memory operands = new fn[](2);
int[] memory coefficients0 = new int[](1);
coefficients0[0] = int(self.one);
operands[0] = newFn(coefficients0, self.one); // f(x) = 1
int[] memory coefficients1 = new int[](2);
coefficients1[1] = int(self.one);
operands[1] = newFn(coefficients1, self.one); // g(x) = x
return newFn(operands, BinaryOp.DIVIDE); // f/g = 1/x
// TODO test
}
// case EXP
return self;
}
function _differentiatePolynomial(fn memory self) private pure returns(fn memory) {
uint coefLen = self.coefficients.length;
int[] memory coefficients = new int[](coefLen-1);
for (uint i=0; i<coefLen-1; i++) {
coefficients[i] = self.coefficients[i+1] * int(i+1);
}
return newFn(coefficients, self.scalar, self.one);
}
// TODO test correctness
function _differentiateBinaryOp(fn memory self) private pure returns(fn memory) {
fn[] memory dfs = new fn[](2);
dfs[0] = differentiate(self.operands[0]); // f'
dfs[1] = differentiate(self.operands[1]); // g'
fn[] memory factors0 = new fn[](2);
if (self.op == BinaryOp.COMPOSITION) {
factors0[0] = dfs[1]; // g'
factors0[1] = compose(dfs[0], self.operands[1]); // f'(g)
return newFn(factors0, BinaryOp.MULTIPLY);
}
if (self.op < BinaryOp.MULTIPLY) { // +,-
// d op = op d
return newFn(dfs, self.op);
}
factors0[0] = self.operands[0];
factors0[1] = dfs[1];
fn[] memory factors1 = new fn[](2);
factors1[0] = self.operands[1];
factors1[1] = dfs[0];
fn[] memory summands = new fn[](2);
summands[0] = newFn(factors1, BinaryOp.MULTIPLY);
summands[1] = newFn(factors0, BinaryOp.MULTIPLY);
if (self.op == BinaryOp.MULTIPLY) {
// a*b' + a'*b
return newFn(summands, BinaryOp.ADD);
} // self.op == BinaryOp.DIVIDE
// (low * dHigh - high * dLow) / (low)^2 :)
fn[] memory operands = new fn[](2);
operands[0] = newFn(summands, BinaryOp.SUBTRACT);
fn[] memory lows = new fn[](2);
lows[0] = self.operands[1];
lows[1] = self.operands[1];
operands[1] = newFn(lows, BinaryOp.MULTIPLY);
return newFn(operands, BinaryOp.DIVIDE);
}
function generalAntiderivative(fn memory self) internal pure returns(fn memory) {
/*if (self.form == Form.CONSTANT) {
// TODO
}
if (self.form > Form.POLYNOMIAL)
return // TODO
if (self.form == Form.POLYNOMIAL)
return // TODO
return // TODO
*/
}
function definiteIntegral(fn memory self, int[] memory boundary) internal pure returns(Number memory) {
// TODO
}
}
| else form == TRANSCENDENTAL | function evaluate(fn memory self, int input, uint accuracy, uint[] memory factorialReciprocalsLookupTable) internal pure returns(Number memory) {
require(self.form != Form.CONSTANT, "cannot evaluate a constant form.");
if (self.form == Form.BINARYOP)
return _evaluateBinaryOperation(self, input, accuracy, factorialReciprocalsLookupTable);
if (self.form == Form.POLYNOMIAL)
return _evaluatePolynomial(self, input);
return _evaluateTranscendental(self, input, accuracy, factorialReciprocalsLookupTable);
}
return _evaluatePolynomial(self, input);
| 12,559,552 |
./partial_match/1/0xEDb07875051B26b56747e738efB3d7a271d9145e/sources/contracts/interfaces/ISandwichBotProxy.sol | SPDX-License-Identifier: GNU-GPL | interface ISandwichBotProxy {
function proxyCall(bytes32 poolId, address[] memory targets, uint[] memory values, bytes[] memory calldatas) external;
function setResonateHelper(address _resonateHelper) external;
function sandwichSnapshot(
bytes32 poolId,
uint amount,
bool isWithdrawal
) external;
} | 4,232,484 |
/**
*Submitted for verification at Etherscan.io on 2022-02-27
*/
// 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);
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev 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 Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @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 Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
/**
* @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 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;
}
/**
* @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);
}
}
contract WastedWorld is Ownable, ReentrancyGuard {
uint256 public constant SECONDS_IN_DAY = 24 * 60 * 60;
uint256 public constant ACCELERATED_YIELD_DAYS = 2;
uint256 public constant ACCELERATED_YIELD_MULTIPLIER = 2;
uint256 public acceleratedYield;
address public signerAddress;
address[] public authorisedLog;
bool public stakingLaunched;
bool public depositPaused;
struct Staker {
uint256 currentYield;
uint256 accumulatedAmount;
uint256 lastCheckpoint;
}
mapping(address => bool) isWWNftContract;
mapping(address => mapping(address => uint256[])) stakedTokensForAddress;
mapping(address => uint256) public _baseRates;
mapping(address => Staker) private _stakers;
mapping(address => mapping(uint256 => address)) private _ownerOfToken;
mapping(address => mapping(uint256 => uint256)) private _tokensMultiplier;
mapping(address => bool) private _authorised;
event Deposit(address indexed staker,address contractAddress,uint256 tokensAmount);
event Withdraw(address indexed staker,address contractAddress,uint256 tokensAmount);
event AutoDeposit(address indexed contractAddress,uint256 tokenId,address indexed owner);
event WithdrawStuckERC721(address indexed receiver, address indexed tokenAddress, uint256 indexed tokenId);
constructor(
address _pre,
address _signer
) {
_baseRates[_pre] = 4200 ether;
isWWNftContract[_pre] = true;
signerAddress = _signer;
}
modifier authorised() {
require(_authorised[_msgSender()], "The token contract is not authorised");
_;
}
function deposit(
address contractAddress,
uint256[] memory tokenIds,
uint256[] memory tokenTraits,
bytes calldata signature
) public nonReentrant {
require(!depositPaused, "Deposit paused");
require(stakingLaunched, "Staking is not launched yet");
require(
contractAddress != address(0) &&
isWWNftContract[contractAddress],
"Unknown contract"
);
if (tokenTraits.length > 0) {
require(_validateSignature(
signature,
contractAddress,
tokenIds,
tokenTraits
), "Invalid data provided");
_setTokensValues(contractAddress, tokenIds, tokenTraits);
}
Staker storage user = _stakers[_msgSender()];
uint256 newYield = user.currentYield;
for (uint256 i; i < tokenIds.length; i++) {
require(IERC721(contractAddress).ownerOf(tokenIds[i]) == _msgSender(), "Not the owner");
IERC721(contractAddress).safeTransferFrom(_msgSender(), address(this), tokenIds[i]);
_ownerOfToken[contractAddress][tokenIds[i]] = _msgSender();
newYield += getTokenYield(contractAddress, tokenIds[i]);
stakedTokensForAddress[_msgSender()][contractAddress].push(tokenIds[i]);
}
accumulate(_msgSender());
user.currentYield = newYield;
emit Deposit(_msgSender(), contractAddress, tokenIds.length);
}
function withdraw(
address contractAddress,
uint256[] memory tokenIds
) public nonReentrant {
require(
contractAddress != address(0) &&
isWWNftContract[contractAddress],
"Unknown contract"
);
Staker storage user = _stakers[_msgSender()];
uint256 newYield = user.currentYield;
for (uint256 i; i < tokenIds.length; i++) {
require(IERC721(contractAddress).ownerOf(tokenIds[i]) == address(this), "Not the owner");
_ownerOfToken[contractAddress][tokenIds[i]] = address(0);
if (user.currentYield != 0) {
uint256 tokenYield = getTokenYield(contractAddress, tokenIds[i]);
newYield -= tokenYield;
}
stakedTokensForAddress[_msgSender()][contractAddress] = _moveTokenInTheList(stakedTokensForAddress[_msgSender()][contractAddress], tokenIds[i]);
stakedTokensForAddress[_msgSender()][contractAddress].pop();
IERC721(contractAddress).safeTransferFrom(address(this), _msgSender(), tokenIds[i]);
}
accumulate(_msgSender());
user.currentYield = newYield;
emit Withdraw(_msgSender(), contractAddress, tokenIds.length);
}
function registerDeposit(address owner, address contractAddress, uint256 tokenId) public authorised {
require(
contractAddress != address(0) &&
isWWNftContract[contractAddress],
"Unknown contract"
);
require(IERC721(contractAddress).ownerOf(tokenId) == address(this), "!Owner");
require(ownerOf(contractAddress, tokenId) == address(0), "Already deposited");
_ownerOfToken[contractAddress][tokenId] = owner;
Staker storage user = _stakers[owner];
uint256 newYield = user.currentYield;
newYield += getTokenYield(contractAddress, tokenId);
stakedTokensForAddress[owner][contractAddress].push(tokenId);
accumulate(owner);
user.currentYield = newYield;
emit AutoDeposit(contractAddress, tokenId, _msgSender());
}
function getAccumulatedAmount(address staker) external view returns (uint256) {
return _stakers[staker].accumulatedAmount + getCurrentReward(staker);
}
function getTokenYield(address contractAddress, uint256 tokenId) public view returns (uint256) {
uint256 tokenYield = _tokensMultiplier[contractAddress][tokenId];
if (tokenYield == 0) { tokenYield = _baseRates[contractAddress]; }
return tokenYield;
}
function getStakerYield(address staker) public view returns (uint256) {
return _stakers[staker].currentYield;
}
function getStakerTokens(address staker, address contractAddress) public view returns (uint256[] memory) {
return (stakedTokensForAddress[staker][contractAddress]);
}
function isMultiplierSet(address contractAddress, uint256 tokenId) public view returns (bool) {
return _tokensMultiplier[contractAddress][tokenId] > 0;
}
function _moveTokenInTheList(uint256[] memory list, uint256 tokenId) internal pure returns (uint256[] memory) {
uint256 tokenIndex = 0;
uint256 lastTokenIndex = list.length - 1;
uint256 length = list.length;
for(uint256 i = 0; i < length; i++) {
if (list[i] == tokenId) {
tokenIndex = i + 1;
break;
}
}
require(tokenIndex != 0, "msg.sender is not the owner");
tokenIndex -= 1;
if (tokenIndex != lastTokenIndex) {
list[tokenIndex] = list[lastTokenIndex];
list[lastTokenIndex] = tokenId;
}
return list;
}
function _validateSignature(
bytes calldata signature,
address contractAddress,
uint256[] memory tokenIds,
uint256[] memory tokenTraits
) internal view returns (bool) {
bytes32 dataHash = keccak256(abi.encodePacked(contractAddress, tokenIds, tokenTraits));
bytes32 message = ECDSA.toEthSignedMessageHash(dataHash);
address receivedAddress = ECDSA.recover(message, signature);
return (receivedAddress != address(0) && receivedAddress == signerAddress);
}
function _setTokensValues(
address contractAddress,
uint256[] memory tokenIds,
uint256[] memory tokenTraits
) internal {
require(tokenIds.length == tokenTraits.length, "Wrong arrays provided");
for (uint256 i; i < tokenIds.length; i++) {
if (tokenTraits[i] != 0 && tokenTraits[i] <= 8000 ether) {
_tokensMultiplier[contractAddress][tokenIds[i]] = tokenTraits[i];
}
}
}
function getCurrentReward(address staker) public view returns (uint256) {
Staker memory user = _stakers[staker];
if (user.lastCheckpoint == 0) { return 0; }
if (user.lastCheckpoint < acceleratedYield && block.timestamp < acceleratedYield) {
return (block.timestamp - user.lastCheckpoint) * user.currentYield / SECONDS_IN_DAY * ACCELERATED_YIELD_MULTIPLIER;
}
if (user.lastCheckpoint < acceleratedYield && block.timestamp > acceleratedYield) {
uint256 currentReward;
currentReward += (acceleratedYield - user.lastCheckpoint) * user.currentYield / SECONDS_IN_DAY * ACCELERATED_YIELD_MULTIPLIER;
currentReward += (block.timestamp - acceleratedYield) * user.currentYield / SECONDS_IN_DAY;
return currentReward;
}
return (block.timestamp - user.lastCheckpoint) * user.currentYield / SECONDS_IN_DAY;
}
function accumulate(address staker) internal {
_stakers[staker].accumulatedAmount += getCurrentReward(staker);
_stakers[staker].lastCheckpoint = block.timestamp;
}
/**
* @dev Returns token owner address (returns address(0) if token is not inside the gateway)
*/
function ownerOf(address contractAddress, uint256 tokenId) public view returns (address) {
return _ownerOfToken[contractAddress][tokenId];
}
function addNFTContract(address _contract, uint256 _baseReward) public onlyOwner {
_baseRates[_contract] = _baseReward;
isWWNftContract[_contract] = true;
}
/**
* @dev Admin function to authorise the contract address
*/
function authorise(address toAuth) public onlyOwner {
_authorised[toAuth] = true;
authorisedLog.push(toAuth);
}
/**
* @dev Function allows admin add unauthorised address.
*/
function unauthorise(address addressToUnAuth) public onlyOwner {
_authorised[addressToUnAuth] = false;
}
/**
* @dev Function allows admin withdraw ERC721 in case of emergency.
*/
function emergencyWithdraw(address tokenAddress, uint256[] memory tokenIds) public onlyOwner {
require(tokenIds.length <= 50, "50 is max per tx");
pauseDeposit(true);
for (uint256 i; i < tokenIds.length; i++) {
address receiver = _ownerOfToken[tokenAddress][tokenIds[i]];
if (receiver != address(0) && IERC721(tokenAddress).ownerOf(tokenIds[i]) == address(this)) {
IERC721(tokenAddress).transferFrom(address(this), receiver, tokenIds[i]);
emit WithdrawStuckERC721(receiver, tokenAddress, tokenIds[i]);
}
}
}
/**
* @dev Function allows to pause deposits if needed. Withdraw remains active.
*/
function pauseDeposit(bool _pause) public onlyOwner {
depositPaused = _pause;
}
/**
* @dev Function allows to pause deposits if needed. Withdraw remains active.
*/
function updateSignerAddress(address _signer) public onlyOwner {
signerAddress = _signer;
}
function launchStaking() public onlyOwner {
require(!stakingLaunched, "Staking has been launched already");
stakingLaunched = true;
acceleratedYield = block.timestamp + (SECONDS_IN_DAY * ACCELERATED_YIELD_DAYS);
}
function updateBaseYield(address _contract, uint256 _yield) public onlyOwner {
_baseRates[_contract] = _yield;
}
function onERC721Received(address, address, uint256, bytes calldata) external pure returns(bytes4){
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
} | Admin function to authorise the contract address/ | function authorise(address toAuth) public onlyOwner {
_authorised[toAuth] = true;
authorisedLog.push(toAuth);
}
| 14,720,803 |
./full_match/80001/0xe1F5C4130c6f4e67E1c216d638133e2FdF95A5c1/sources/contracts/TimeLock.sol | increaseWithdrawTime() | function increaseWithdrawTime(uint _counterID, uint _increaseTime) public {
OwnerInfo storage ownerInfo = ownerInfoMapping[_counterID];
require(
msg.sender == ownerInfo.owner,
"only owner can update deposit amount"
);
ownerInfo.unlockTime += _increaseTime;
}
| 5,668,113 |
./partial_match/3/0x0AAd60Be63Bfa5a4A43C601663edc709C1CFaA2A/sources/MasterChef.sol | Safe DOGS transfer function, just in case if rounding error causes pool to not have enough DogSwap. | function safeDOGSTransfer(address _to, uint256 _amount) internal {
uint256 DOGSBal = DOGS.balanceOf(address(this));
if (_amount > DOGSBal) {
DOGS.transfer(_to, DOGSBal);
DOGS.transfer(_to, _amount);
}
}
| 5,199,122 |
pragma solidity ^0.4.15;
/**
* @title Doneth (Doneth)
* @dev Doneth is a contract that allows shared access to funds
* in the form of Ether and ERC20 tokens. It is especially relevant
* to donation based projects. The admins of the contract determine
* who is a member, and each member gets a number of shares. The
* number of shares each member has determines how much Ether/ERC20
* the member can withdraw from the contract.
*/
/*
* Ownable
*
* Base contract with an owner.
* Provides onlyOwner modifier, which prevents function from running
* if it is called by anyone other than the owner.
*/
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Doneth is Ownable {
using SafeMath for uint256;
// Name of the contract
string public name;
// Sum of all shares allocated to members
uint256 public totalShares;
// Sum of all withdrawals done by members
uint256 public totalWithdrawn;
// Block number of when the contract was created
uint256 public genesisBlockNumber;
// Number of decimal places for floating point division
uint256 constant public PRECISION = 18;
// Variables for shared expense allocation
uint256 public sharedExpense;
uint256 public sharedExpenseWithdrawn;
// Used to keep track of members
mapping(address => Member) public members;
address[] public memberKeys;
struct Member {
bool exists;
bool admin;
uint256 shares;
uint256 withdrawn;
string memberName;
mapping(address => uint256) tokensWithdrawn;
}
// Used to keep track of ERC20 tokens used and how much withdrawn
mapping(address => Token) public tokens;
address[] public tokenKeys;
struct Token {
bool exists;
uint256 totalWithdrawn;
}
function Doneth(string _contractName, string _founderName) {
if (bytes(_contractName).length > 21) revert();
if (bytes(_founderName).length > 21) revert();
name = _contractName;
genesisBlockNumber = block.number;
addMember(msg.sender, 1, true, _founderName);
}
event Deposit(address from, uint value);
event Withdraw(address from, uint value, uint256 newTotalWithdrawn);
event TokenWithdraw(address from, uint value, address token, uint amount);
event AddShare(address who, uint256 addedShares, uint256 newTotalShares);
event RemoveShare(address who, uint256 removedShares, uint256 newTotalShares);
event ChangePrivilege(address who, bool oldValue, bool newValue);
event ChangeContractName(string oldValue, string newValue);
event ChangeMemberName(address who, string oldValue, string newValue);
event ChangeSharedExpense(uint256 contractBalance, uint256 oldValue, uint256 newValue);
event WithdrawSharedExpense(address from, address to, uint value, uint256 newSharedExpenseWithdrawn);
// Fallback function accepts Ether from donators
function () public payable {
Deposit(msg.sender, msg.value);
}
modifier onlyAdmin() {
if (msg.sender != owner && !members[msg.sender].admin) revert();
_;
}
modifier onlyExisting(address who) {
if (!members[who].exists) revert();
_;
}
// Series of getter functions for contract data
function getMemberCount() public constant returns(uint) {
return memberKeys.length;
}
function getMemberAtKey(uint key) public constant returns(address) {
return memberKeys[key];
}
function getBalance() public constant returns(uint256 balance) {
return this.balance;
}
function getContractInfo() public constant returns(string, address, uint256, uint256, uint256) {
return (string(name), owner, genesisBlockNumber, totalShares, totalWithdrawn);
}
function returnMember(address _address) public constant onlyExisting(_address) returns(bool admin, uint256 shares, uint256 withdrawn, string memberName) {
Member memory m = members[_address];
return (m.admin, m.shares, m.withdrawn, m.memberName);
}
function checkERC20Balance(address token) public constant returns(uint256) {
uint256 balance = ERC20(token).balanceOf(address(this));
if (!tokens[token].exists && balance > 0) {
tokens[token].exists = true;
}
return balance;
}
// Function to add members to the contract
function addMember(address who, uint256 shares, bool admin, string memberName) public onlyAdmin() {
// Don't allow the same member to be added twice
if (members[who].exists) revert();
if (bytes(memberName).length > 21) revert();
Member memory newMember;
newMember.exists = true;
newMember.admin = admin;
newMember.memberName = memberName;
members[who] = newMember;
memberKeys.push(who);
addShare(who, shares);
}
function updateMember(address who, uint256 shares, bool isAdmin, string name) public onlyAdmin() {
if (sha3(members[who].memberName) != sha3(name)) changeMemberName(who, name);
if (members[who].admin != isAdmin) changeAdminPrivilege(who, isAdmin);
if (members[who].shares != shares) allocateShares(who, shares);
}
// Only owner, admin or member can change member's name
function changeMemberName(address who, string newName) public onlyExisting(who) {
if (msg.sender != who && msg.sender != owner && !members[msg.sender].admin) revert();
if (bytes(newName).length > 21) revert();
ChangeMemberName(who, members[who].memberName, newName);
members[who].memberName = newName;
}
function changeAdminPrivilege(address who, bool newValue) public onlyAdmin() {
ChangePrivilege(who, members[who].admin, newValue);
members[who].admin = newValue;
}
// Only admins and owners can change the contract name
function changeContractName(string newName) public onlyAdmin() {
if (bytes(newName).length > 21) revert();
ChangeContractName(name, newName);
name = newName;
}
// Shared expense allocation allows admins to withdraw an amount to be used for shared
// expenses. Shared expense allocation subtracts from the total balance of the contract.
// Only owner can change this amount.
function changeSharedExpenseAllocation(uint256 newAllocation) public onlyOwner() {
if (newAllocation < sharedExpenseWithdrawn) revert();
if (newAllocation.sub(sharedExpenseWithdrawn) > this.balance) revert();
ChangeSharedExpense(this.balance, sharedExpense, newAllocation);
sharedExpense = newAllocation;
}
// Set share amount explicitly by calculating difference then adding or removing accordingly
function allocateShares(address who, uint256 amount) public onlyAdmin() onlyExisting(who) {
uint256 currentShares = members[who].shares;
if (amount == currentShares) revert();
if (amount > currentShares) {
addShare(who, amount.sub(currentShares));
} else {
removeShare(who, currentShares.sub(amount));
}
}
// Increment the number of shares for a member
function addShare(address who, uint256 amount) public onlyAdmin() onlyExisting(who) {
totalShares = totalShares.add(amount);
members[who].shares = members[who].shares.add(amount);
AddShare(who, amount, members[who].shares);
}
// Decrement the number of shares for a member
function removeShare(address who, uint256 amount) public onlyAdmin() onlyExisting(who) {
totalShares = totalShares.sub(amount);
members[who].shares = members[who].shares.sub(amount);
RemoveShare(who, amount, members[who].shares);
}
// Function for a member to withdraw Ether from the contract proportional
// to the amount of shares they have. Calculates the totalWithdrawableAmount
// in Ether based on the member's share and the Ether balance of the contract,
// then subtracts the amount of Ether that the member has already previously
// withdrawn.
function withdraw(uint256 amount) public onlyExisting(msg.sender) {
uint256 newTotal = calculateTotalWithdrawableAmount(msg.sender);
if (amount > newTotal.sub(members[msg.sender].withdrawn)) revert();
members[msg.sender].withdrawn = members[msg.sender].withdrawn.add(amount);
totalWithdrawn = totalWithdrawn.add(amount);
msg.sender.transfer(amount);
Withdraw(msg.sender, amount, totalWithdrawn);
}
// Withdrawal function for ERC20 tokens
function withdrawToken(uint256 amount, address token) public onlyExisting(msg.sender) {
uint256 newTotal = calculateTotalWithdrawableTokenAmount(msg.sender, token);
if (amount > newTotal.sub(members[msg.sender].tokensWithdrawn[token])) revert();
members[msg.sender].tokensWithdrawn[token] = members[msg.sender].tokensWithdrawn[token].add(amount);
tokens[token].totalWithdrawn = tokens[token].totalWithdrawn.add(amount);
ERC20(token).transfer(msg.sender, amount);
TokenWithdraw(msg.sender, amount, token, tokens[token].totalWithdrawn);
}
// Withdraw from shared expense allocation. Total withdrawable is calculated as
// sharedExpense minus sharedExpenseWithdrawn. Only Admin can withdraw from shared expense.
function withdrawSharedExpense(uint256 amount, address to) public onlyAdmin() {
if (amount > calculateTotalExpenseWithdrawableAmount()) revert();
sharedExpenseWithdrawn = sharedExpenseWithdrawn.add(amount);
to.transfer(amount);
WithdrawSharedExpense(msg.sender, to, amount, sharedExpenseWithdrawn);
}
// Converts from shares to Eth.
// Ex: 2 shares, 4 total shares, 40 Eth balance
// 40 Eth / 4 total shares = 10 eth per share * 2 shares = 20 Eth to cash out
function calculateTotalWithdrawableAmount(address who) public constant onlyExisting(who) returns (uint256) {
// Total balance to calculate share from =
// contract balance + totalWithdrawn - sharedExpense + sharedExpenseWithdrawn
uint256 balanceSum = this.balance.add(totalWithdrawn);
balanceSum = balanceSum.sub(sharedExpense);
balanceSum = balanceSum.add(sharedExpenseWithdrawn);
// Need to use parts-per notation to compute percentages for lack of floating point division
uint256 ethPerSharePPN = balanceSum.percent(totalShares, PRECISION);
uint256 ethPPN = ethPerSharePPN.mul(members[who].shares);
uint256 ethVal = ethPPN.div(10**PRECISION);
return ethVal;
}
function calculateTotalWithdrawableTokenAmount(address who, address token) public constant returns(uint256) {
uint256 balanceSum = checkERC20Balance(token).add(tokens[token].totalWithdrawn);
// Need to use parts-per notation to compute percentages for lack of floating point division
uint256 tokPerSharePPN = balanceSum.percent(totalShares, PRECISION);
uint256 tokPPN = tokPerSharePPN.mul(members[who].shares);
uint256 tokVal = tokPPN.div(10**PRECISION);
return tokVal;
}
function calculateTotalExpenseWithdrawableAmount() public constant returns(uint256) {
return sharedExpense.sub(sharedExpenseWithdrawn);
}
// Used for testing
function delegatePercent(uint256 a, uint256 b, uint256 c) public constant returns (uint256) {
return a.percent(b, c);
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
// Using from SO: https://stackoverflow.com/questions/42738640/division-in-ethereum-solidity/42739843#42739843
// Adapted to use SafeMath and uint256.
function percent(uint256 numerator, uint256 denominator, uint256 precision) internal constant returns(uint256 quotient) {
// caution, check safe-to-multiply here
uint256 _numerator = mul(numerator, 10 ** (precision+1));
// with rounding of last digit
uint256 _quotient = (div(_numerator, denominator) + 5) / 10;
return (_quotient);
}
} | Decrement the number of shares for a member | function removeShare(address who, uint256 amount) public onlyAdmin() onlyExisting(who) {
totalShares = totalShares.sub(amount);
members[who].shares = members[who].shares.sub(amount);
RemoveShare(who, amount, members[who].shares);
}
| 2,560,821 |
./partial_match/42/0x724BEa324E906F8438fC8Ae4512987cf6694642D/sources/CyclopsBank.sol | all rewards for all customers deposits including 0 for empty deposits | function rewardsPerDeposits(address cust_wallet) external view returns (uint32[] memory,uint256[] memory) {
require(cust_wallet == msg.sender || msg.sender == owner, "9");
require(customers_deposits[cust_wallet].length >0, "10");
uint256[] memory rewards = new uint256[](customers_deposits[cust_wallet].length);
uint32[] memory profileIds = new uint32[](customers_deposits[cust_wallet].length);
uint256 reward = 0;
for(uint256 i=0; i < customers_deposits[cust_wallet].length; i++){
Deposit memory dep = customers_deposits[cust_wallet][i];
if (!depositIsActive(dep)){
reward = 0;
reward = depositReward(dep);
}
rewards[i] = reward;
profileIds[i] = dep.deposit_profile_id;
}
return (profileIds, rewards);
for(uint256 i=0; i < customers_deposits[cust_wallet].length; i++){
Deposit memory dep = customers_deposits[cust_wallet][i];
if (!depositIsActive(dep)){
reward = 0;
reward = depositReward(dep);
}
rewards[i] = reward;
profileIds[i] = dep.deposit_profile_id;
}
return (profileIds, rewards);
} else {
}
| 3,363,847 |
./full_match/1/0xE7C2016f5344858f6A1874424d077aDD3ea81fa5/sources/@aragon/govern-core/contracts/pipelines/GovernQueue.sol | release all collateral to submitter | function _executeApproved(ERC3000Data.Container memory _container) internal returns (bytes32 failureMap, bytes[] memory) {
bytes32 containerHash = _container.hash();
queue[containerHash].checkAndSetState(
GovernQueueStateLib.State.Approved,
GovernQueueStateLib.State.Executed
);
_container.config.scheduleDeposit.releaseTo(_container.payload.submitter);
_container.config.challengeDeposit.releaseTo(_container.payload.submitter);
return _execute(_container.payload, containerHash);
}
| 4,907,049 |
pragma solidity 0.4.26;
import "./Oraclize.sol";
/**
* @title Atomic Loans CryptoWatch Oraclize Contract
* @author Atomic Loans
*/
contract CryptoWatch is Oraclize {
/**
* @notice Construct a new CryptoWatch Oraclize Oracle
* @param med_ The address of the Medianizer
* @param medm_ The address of the MakerDAO Medianizer
* @param weth_ The WETH token address
*/
constructor(MedianizerInterface med_, MedianizerInterface medm_, WETH weth_) public Oraclize(med_, medm_, weth_) {}
/**
* @notice Creates request for Oraclize to get the BTC price
* @param payment_ The amount of WETH used as payment for Oraclize
*/
function getAssetPrice(uint128 payment_) internal returns (bytes32 queryId) {
weth.withdraw(payment_);
require(oraclize_getPrice("URL", gasLimit) <= address(this).balance, "CryptoWatch.getAssetPrice: Ether balance is less than oraclize price");
queryId = oraclize_query("URL", "json(https://api.cryptowat.ch/markets/coinbase-pro/btcusd/price).result.price", gasLimit);
}
}
| Creates request for Oraclize to get the BTC price payment_ The amount of WETH used as payment for Oraclize/ | function getAssetPrice(uint128 payment_) internal returns (bytes32 queryId) {
weth.withdraw(payment_);
require(oraclize_getPrice("URL", gasLimit) <= address(this).balance, "CryptoWatch.getAssetPrice: Ether balance is less than oraclize price");
}
| 7,225,963 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/cryptography/MerkleProofUpgradeable.sol";
import "interfaces/stakehound/ICumulativeMultiTokenMerkleDistributor.sol";
import "interfaces/stakehound/IStakedToken.sol";
contract Multiplexer is Initializable, AccessControlUpgradeable, ICumulativeMultiTokenMerkleDistributor, PausableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
event RootProposed(uint256 cycle, bytes32 root, bytes32 contentHash, uint256 endBlock);
event RootValidated(uint256 cycle, bytes32 root, bytes32 contentHash, uint256 endBlock);
struct MerkleData {
bytes32 root;
bytes32 contentHash;
uint256 cycle;
uint256 endBlock;
}
bytes32 public constant ROOT_PROPOSER_ROLE = keccak256("ROOT_PROPOSER_ROLE");
bytes32 public constant ROOT_VALIDATOR_ROLE = keccak256("ROOT_VALIDATOR_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE");
MerkleData public lastProposedMerkleData;
MerkleData public lastPublishedMerkleData;
mapping(address => mapping(address => uint256)) public claimed;
mapping(address => uint256) public totalClaimed;
function initialize(
address admin,
address initialProposer,
address initialValidator
) public initializer {
__AccessControl_init();
__Pausable_init_unchained();
_setupRole(DEFAULT_ADMIN_ROLE, admin); // The admin can edit all role permissions
_setupRole(ROOT_PROPOSER_ROLE, initialProposer);
_setupRole(ROOT_VALIDATOR_ROLE, initialValidator);
}
/// ===== Modifiers =====
/// @notice Admins can approve new root updaters or admins
function _onlyAdmin() internal view {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "onlyAdmin");
}
/// @notice Root updaters can update the root
function _onlyRootProposer() internal view {
require(hasRole(ROOT_PROPOSER_ROLE, msg.sender), "onlyRootProposer");
}
function _onlyRootValidator() internal view {
require(hasRole(ROOT_VALIDATOR_ROLE, msg.sender), "onlyRootValidator");
}
function _onlyPauser() internal view {
require(hasRole(PAUSER_ROLE, msg.sender), "onlyGuardian");
}
function _onlyUnpauser() internal view {
require(hasRole(UNPAUSER_ROLE, msg.sender), "onlyGuardian");
}
function getCurrentMerkleData() external view returns (MerkleData memory) {
return lastPublishedMerkleData;
}
function getPendingMerkleData() external view returns (MerkleData memory) {
return lastProposedMerkleData;
}
function hasPendingRoot() external view returns (bool) {
return lastProposedMerkleData.cycle == lastPublishedMerkleData.cycle.add(1);
}
function valueFromShares(address _stakedToken, uint256 shares) internal view returns (uint256) {
uint256 sharesPerToken = IStakedToken(_stakedToken).totalShares() / IStakedToken(_stakedToken).totalSupply();
return shares / sharesPerToken;
}
function getClaimedFor(address user, address[] memory tokens) public view returns (address[] memory, uint256[] memory) {
uint256[] memory userClaimed = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
userClaimed[i] = claimed[user][tokens[i]];
}
return (tokens, userClaimed);
}
function encodeClaim(
address[] calldata tokens,
uint256[] calldata cumulativeAmounts,
uint256[] calldata cumulativeStAmounts,
address account,
uint256 cycle
) public view returns (bytes memory encoded, bytes32 hash) {
encoded = abi.encode(account, cycle, tokens, cumulativeAmounts, cumulativeStAmounts);
hash = keccak256(encoded);
}
/// @notice Claim accumulated rewards for a set of tokens at a given cycle number
/// @notice First part of tokens are normal ERC20, second part of tokens are stTokens
function claim(
address[] calldata tokens,
uint256[] calldata cumulativeAmounts,
uint256[] calldata cumulativeStAmounts,
uint256 cycle,
bytes32[] calldata merkleProof
) external whenNotPaused {
require(cycle == lastPublishedMerkleData.cycle, "Invalid cycle");
{
// Fix stack too deep
// Verify the merkle proof.
bytes32 node = keccak256(abi.encode(msg.sender, cycle, tokens, cumulativeAmounts, cumulativeStAmounts));
require(MerkleProofUpgradeable.verify(merkleProof, lastPublishedMerkleData.root, node), "Invalid proof");
}
// Claim each token
uint256 cumALen = cumulativeAmounts.length;
// First we claim the normal ERC20 tokens
for (uint256 i; i < cumALen; i++) {
address token = tokens[i];
uint256 cumAmt = cumulativeAmounts[i];
uint256 claimable = cumAmt.sub(claimed[msg.sender][token]);
require(claimable > 0, "Excessive claim");
claimed[msg.sender][token] = claimed[msg.sender][token].add(claimable);
require(claimed[msg.sender][token] == cumAmt, "Claimed amount mismatch");
IERC20Upgradeable(token).safeTransfer(msg.sender, claimable);
emit Claimed(msg.sender, tokens[i], claimable, cycle, now, block.number);
}
uint256 cumStALen = cumulativeStAmounts.length;
for (uint256 i = 0; i < cumStALen; i++) {
address token = tokens[cumALen + i];
uint256 cumStAmt = cumulativeStAmounts[i];
uint256 claimable = cumStAmt.sub(claimed[msg.sender][token]);
require(claimable > 0, "Excessive claim");
claimed[msg.sender][token] = claimed[msg.sender][token].add(claimable);
require(claimed[msg.sender][token] == cumStAmt, "Claimed amount mismatch");
IERC20Upgradeable(token).safeTransfer(msg.sender, valueFromShares(token, claimable));
emit Claimed(msg.sender, token, claimable, cycle, now, block.number);
}
}
// ===== Root Updater Restricted =====
/// @notice Propose a new root and content hash, which will be stored as pending until approved
function proposeRoot(
bytes32 root,
bytes32 contentHash,
uint256 cycle,
uint256 endBlock
) external whenNotPaused {
_onlyRootProposer();
require(cycle == lastPublishedMerkleData.cycle.add(1), "Incorrect cycle");
require(endBlock > lastProposedMerkleData.endBlock, "Cannot publish root with earlier end block");
require(block.number.sub(endBlock) >= 30, "Endblock must be at least 30 blocks behind");
lastProposedMerkleData = MerkleData(root, contentHash, cycle, endBlock);
emit RootProposed(cycle, root, contentHash, endBlock);
}
/// ===== Root Validator Restricted =====
/// @notice Approve the current pending root and content hash
function approveRoot(
bytes32 root,
bytes32 contentHash,
uint256 cycle,
uint256 endBlock
) external whenNotPaused {
_onlyRootValidator();
require(root == lastProposedMerkleData.root, "Incorrect root");
require(contentHash == lastProposedMerkleData.contentHash, "Incorrect content hash");
require(cycle == lastProposedMerkleData.cycle, "Incorrect cycle");
require(endBlock == lastProposedMerkleData.endBlock, "Incorrect cycle end block");
lastPublishedMerkleData = MerkleData(root, contentHash, cycle, endBlock);
emit RootValidated(cycle, root, contentHash, endBlock);
}
/// ===== Guardian Restricted =====
/// @notice Pause publishing of new roots
function pause() external {
_onlyPauser();
_pause();
}
/// @notice Unpause publishing of new roots
function unpause() external {
_onlyUnpauser();
_unpause();
}
}
| Approve the current pending root and content hash | function approveRoot(
bytes32 root,
bytes32 contentHash,
uint256 cycle,
uint256 endBlock
) external whenNotPaused {
_onlyRootValidator();
require(root == lastProposedMerkleData.root, "Incorrect root");
require(contentHash == lastProposedMerkleData.contentHash, "Incorrect content hash");
require(cycle == lastProposedMerkleData.cycle, "Incorrect cycle");
require(endBlock == lastProposedMerkleData.endBlock, "Incorrect cycle end block");
lastPublishedMerkleData = MerkleData(root, contentHash, cycle, endBlock);
emit RootValidated(cycle, root, contentHash, endBlock);
}
| 12,921,011 |
./full_match/80001/0x5c6D4D4b00441C1b6dBCF97291cAcb49BC1edb4B/sources/project_/contracts/MBOSpecialCollection.sol | =============== Owner Functions =============== Changes the address of the MBO Genesis NFT contract newGenesisNFTContract The address of the new MBO Genesis NFT contract/ | function changeGenesisNFTContract(address newGenesisNFTContract) public onlyOwner {
MBOGenesisNFTContract = MBO_GENESIS_NFT_CONTRACT(newGenesisNFTContract);
}
| 857,356 |
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @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 OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Escrow (based on openzeppelin version with one function to withdraw funds to the wallet)
* @dev Base escrow contract, holds funds destinated to a payee until they
* withdraw them. The contract that uses the escrow as its payment method
* should be its owner, and provide public methods redirecting to the escrow's
* deposit and withdraw.
*/
contract Escrow is Ownable {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private deposits;
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param _payee The destination address of the funds.
*/
function deposit(address _payee) public onlyOwner payable {
uint256 amount = msg.value;
deposits[_payee] = deposits[_payee].add(amount);
emit Deposited(_payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee.
* @param _payee The address whose funds will be withdrawn and transferred to.
* @return Amount withdrawn
*/
function withdraw(address _payee) public onlyOwner returns(uint256) {
uint256 payment = deposits[_payee];
assert(address(this).balance >= payment);
deposits[_payee] = 0;
_payee.transfer(payment);
emit Withdrawn(_payee, payment);
return payment;
}
/**
* @dev Withdraws the wallet's funds.
* @param _wallet address the funds will be transferred to.
*/
function beneficiaryWithdraw(address _wallet) public onlyOwner {
uint256 _amount = address(this).balance;
_wallet.transfer(_amount);
emit Withdrawn(_wallet, _amount);
}
/**
* @dev Returns the deposited amount of the given address.
* @param _payee address of the payee of which to return the deposted amount.
* @return Deposited amount by the address given as argument.
*/
function depositsOf(address _payee) public view returns(uint256) {
return deposits[_payee];
}
}
/**
* @title PullPayment (based on openzeppelin version with one function to withdraw funds to the wallet)
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncTransfer instead of send or transfer.
*/
contract PullPayment {
Escrow private escrow;
constructor() public {
escrow = new Escrow();
}
/**
* @dev Returns the credit owed to an address.
* @param _dest The creditor's address.
* @return Deposited amount by the address given as argument.
*/
function payments(address _dest) public view returns(uint256) {
return escrow.depositsOf(_dest);
}
/**
* @dev Withdraw accumulated balance, called by payee.
* @param _payee The address whose funds will be withdrawn and transferred to.
* @return Amount withdrawn
*/
function _withdrawPayments(address _payee) internal returns(uint256) {
uint256 payment = escrow.withdraw(_payee);
return payment;
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param _dest The destination address of the funds.
* @param _amount The amount to transfer.
*/
function _asyncTransfer(address _dest, uint256 _amount) internal {
escrow.deposit.value(_amount)(_dest);
}
/**
* @dev Withdraws the wallet's funds.
* @param _wallet address the funds will be transferred to.
*/
function _withdrawFunds(address _wallet) internal {
escrow.beneficiaryWithdraw(_wallet);
}
}
/** @title VestedCrowdsale
* @dev Extension of Crowdsale to allow a vested distribution of tokens
* Users have to individually claim their tokens
*/
contract VestedCrowdsale {
using SafeMath for uint256;
mapping (address => uint256) public withdrawn;
mapping (address => uint256) public contributions;
mapping (address => uint256) public contributionsRound;
uint256 public vestedTokens;
/**
* @dev Gives how much a user is allowed to withdraw at the current moment
* @param _beneficiary The address of the user asking how much he's allowed
* to withdraw
* @return Amount _beneficiary is allowed to withdraw
*/
function getWithdrawableAmount(address _beneficiary) public view returns(uint256) {
uint256 step = _getVestingStep(_beneficiary);
uint256 valueByStep = _getValueByStep(_beneficiary);
uint256 result = step.mul(valueByStep).sub(withdrawn[_beneficiary]);
return result;
}
/**
* @dev Gives the step of the vesting (starts from 0 to steps)
* @param _beneficiary The address of the user asking how much he's allowed
* to withdraw
* @return The vesting step for _beneficiary
*/
function _getVestingStep(address _beneficiary) internal view returns(uint8) {
require(contributions[_beneficiary] != 0);
require(contributionsRound[_beneficiary] > 0 && contributionsRound[_beneficiary] < 4);
uint256 march31 = 1554019200;
uint256 april30 = 1556611200;
uint256 may31 = 1559289600;
uint256 june30 = 1561881600;
uint256 july31 = 1564560000;
uint256 sept30 = 1569830400;
uint256 contributionRound = contributionsRound[_beneficiary];
// vesting for private sale contributors
if (contributionRound == 1) {
if (block.timestamp < march31) {
return 0;
}
if (block.timestamp < june30) {
return 1;
}
if (block.timestamp < sept30) {
return 2;
}
return 3;
}
// vesting for pre ico contributors
if (contributionRound == 2) {
if (block.timestamp < april30) {
return 0;
}
if (block.timestamp < july31) {
return 1;
}
return 2;
}
// vesting for ico contributors
if (contributionRound == 3) {
if (block.timestamp < may31) {
return 0;
}
return 1;
}
}
/**
* @dev Gives the amount a user is allowed to withdraw by step
* @param _beneficiary The address of the user asking how much he's allowed
* to withdraw
* @return How much a user is allowed to withdraw by step
*/
function _getValueByStep(address _beneficiary) internal view returns(uint256) {
require(contributions[_beneficiary] != 0);
require(contributionsRound[_beneficiary] > 0 && contributionsRound[_beneficiary] < 4);
uint256 contributionRound = contributionsRound[_beneficiary];
uint256 amount;
uint256 rate;
if (contributionRound == 1) {
rate = 416700;
amount = contributions[_beneficiary].mul(rate).mul(25).div(100);
return amount;
} else if (contributionRound == 2) {
rate = 312500;
amount = contributions[_beneficiary].mul(rate).mul(25).div(100);
return amount;
}
rate = 250000;
amount = contributions[_beneficiary].mul(rate).mul(25).div(100);
return amount;
}
}
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable {
// Whitelisted address
mapping(address => bool) public whitelist;
event AddedBeneficiary(address indexed _beneficiary);
event RemovedBeneficiary(address indexed _beneficiary);
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addAddressToWhitelist(address[] _beneficiaries) public onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
emit AddedBeneficiary(_beneficiaries[i]);
}
}
/**
* @dev Adds list of address to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) public onlyOwner {
whitelist[_beneficiary] = true;
emit AddedBeneficiary(_beneficiary);
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) public onlyOwner {
whitelist[_beneficiary] = false;
emit RemovedBeneficiary(_beneficiary);
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
/**
* @title DSLACrowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether
*/
contract DSLACrowdsale is VestedCrowdsale, Whitelist, Pausable, PullPayment {
// struct to store ico rounds details
struct IcoRound {
uint256 rate;
uint256 individualFloor;
uint256 individualCap;
uint256 softCap;
uint256 hardCap;
}
// mapping ico rounds
mapping (uint256 => IcoRound) public icoRounds;
// The token being sold
ERC20Burnable private _token;
// Address where funds are collected
address private _wallet;
// Amount of wei raised
uint256 private totalContributionAmount;
// Tokens to sell = 5 Billions * 10^18 = 5 * 10^27 = 5000000000000000000000000000
uint256 public constant TOKENSFORSALE = 5000000000000000000000000000;
// Current ico round
uint256 public currentIcoRound;
// Distributed Tokens
uint256 public distributedTokens;
// Amount of wei raised from other currencies
uint256 public weiRaisedFromOtherCurrencies;
// Refund period on
bool public isRefunding = false;
// Finalized crowdsale off
bool public isFinalized = false;
// Refunding deadline
uint256 public refundDeadline;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(address wallet, ERC20Burnable token) public {
require(wallet != address(0) && token != address(0));
icoRounds[1] = IcoRound(
416700,
3 ether,
600 ether,
0,
1200 ether
);
icoRounds[2] = IcoRound(
312500,
12 ether,
5000 ether,
0,
6000 ether
);
icoRounds[3] = IcoRound(
250000,
3 ether,
30 ether,
7200 ether,
17200 ether
);
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _contributor Address performing the token purchase
*/
function buyTokens(address _contributor) public payable {
require(whitelist[_contributor]);
uint256 contributionAmount = msg.value;
_preValidatePurchase(_contributor, contributionAmount, currentIcoRound);
totalContributionAmount = totalContributionAmount.add(contributionAmount);
uint tokenAmount = _handlePurchase(contributionAmount, currentIcoRound, _contributor);
emit TokensPurchased(msg.sender, _contributor, contributionAmount, tokenAmount);
_forwardFunds();
}
/**
* @dev Function to go to the next round
* @return True bool when round is incremented
*/
function goToNextRound() public onlyOwner returns(bool) {
require(currentIcoRound >= 0 && currentIcoRound < 3);
currentIcoRound = currentIcoRound + 1;
return true;
}
/**
* @dev Manually adds a contributor's contribution for private presale period
* @param _contributor The address of the contributor
* @param _contributionAmount Amount of wei contributed
*/
function addPrivateSaleContributors(address _contributor, uint256 _contributionAmount)
public onlyOwner
{
uint privateSaleRound = 1;
_preValidatePurchase(_contributor, _contributionAmount, privateSaleRound);
totalContributionAmount = totalContributionAmount.add(_contributionAmount);
addToWhitelist(_contributor);
_handlePurchase(_contributionAmount, privateSaleRound, _contributor);
}
/**
* @dev Manually adds a contributor's contribution with other currencies
* @param _contributor The address of the contributor
* @param _contributionAmount Amount of wei contributed
* @param _round contribution round
*/
function addOtherCurrencyContributors(address _contributor, uint256 _contributionAmount, uint256 _round)
public onlyOwner
{
_preValidatePurchase(_contributor, _contributionAmount, _round);
weiRaisedFromOtherCurrencies = weiRaisedFromOtherCurrencies.add(_contributionAmount);
addToWhitelist(_contributor);
_handlePurchase(_contributionAmount, _round, _contributor);
}
/**
* @dev Function to close refunding period
* @return True bool
*/
function closeRefunding() public returns(bool) {
require(isRefunding);
require(block.timestamp > refundDeadline);
isRefunding = false;
_withdrawFunds(wallet());
return true;
}
/**
* @dev Function to close the crowdsale
* @return True bool
*/
function closeCrowdsale() public onlyOwner returns(bool) {
require(currentIcoRound > 0 && currentIcoRound < 4);
currentIcoRound = 4;
return true;
}
/**
* @dev Function to finalize the crowdsale
* @param _burn bool burn unsold tokens when true
* @return True bool
*/
function finalizeCrowdsale(bool _burn) public onlyOwner returns(bool) {
require(currentIcoRound == 4 && !isRefunding);
if (raisedFunds() < icoRounds[3].softCap) {
isRefunding = true;
refundDeadline = block.timestamp + 4 weeks;
return true;
}
require(!isFinalized);
_withdrawFunds(wallet());
isFinalized = true;
if (_burn) {
_burnUnsoldTokens();
} else {
_withdrawUnsoldTokens();
}
return true;
}
/**
* @dev Investors can claim refunds here if crowdsale is unsuccessful
*/
function claimRefund() public {
require(isRefunding);
require(block.timestamp <= refundDeadline);
require(payments(msg.sender) > 0);
uint256 payment = _withdrawPayments(msg.sender);
totalContributionAmount = totalContributionAmount.sub(payment);
}
/**
* @dev Allows the sender to claim the tokens he is allowed to withdraw
*/
function claimTokens() public {
require(getWithdrawableAmount(msg.sender) != 0);
uint256 amount = getWithdrawableAmount(msg.sender);
withdrawn[msg.sender] = withdrawn[msg.sender].add(amount);
_deliverTokens(msg.sender, amount);
}
/**
* @dev returns the token being sold
* @return the token being sold
*/
function token() public view returns(ERC20Burnable) {
return _token;
}
/**
* @dev returns the wallet address that collects the funds
* @return the address where funds are collected
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @dev Returns the total of raised funds
* @return total amount of raised funds
*/
function raisedFunds() public view returns(uint256) {
return totalContributionAmount.add(weiRaisedFromOtherCurrencies);
}
// -----------------------------------------
// Internal interface
// -----------------------------------------
/**
* @dev Source of tokens. Override this method to modify the way in which
* the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount)
internal
{
_token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds()
internal
{
if (currentIcoRound == 2 || currentIcoRound == 3) {
_asyncTransfer(msg.sender, msg.value);
} else {
_wallet.transfer(msg.value);
}
}
/**
* @dev Gets tokens allowed to deliver in the given round
* @param _tokenAmount total amount of tokens involved in the purchase
* @param _round Round in which the purchase is happening
* @return Returns the amount of tokens allowed to deliver
*/
function _getTokensToDeliver(uint _tokenAmount, uint _round)
internal pure returns(uint)
{
require(_round > 0 && _round < 4);
uint deliverPercentage = _round.mul(25);
return _tokenAmount.mul(deliverPercentage).div(100);
}
/**
* @dev Handles token purchasing
* @param _contributor Address performing the token purchase
* @param _contributionAmount Value in wei involved in the purchase
* @param _round Round in which the purchase is happening
* @return Returns the amount of tokens purchased
*/
function _handlePurchase(uint _contributionAmount, uint _round, address _contributor)
internal returns(uint) {
uint256 soldTokens = distributedTokens.add(vestedTokens);
uint256 tokenAmount = _getTokenAmount(_contributionAmount, _round);
require(tokenAmount.add(soldTokens) <= TOKENSFORSALE);
contributions[_contributor] = contributions[_contributor].add(_contributionAmount);
contributionsRound[_contributor] = _round;
uint tokensToDeliver = _getTokensToDeliver(tokenAmount, _round);
uint tokensToVest = tokenAmount.sub(tokensToDeliver);
distributedTokens = distributedTokens.add(tokensToDeliver);
vestedTokens = vestedTokens.add(tokensToVest);
_deliverTokens(_contributor, tokensToDeliver);
return tokenAmount;
}
/**
* @dev Validation of an incoming purchase.
* @param _contributor Address performing the token purchase
* @param _contributionAmount Value in wei involved in the purchase
* @param _round Round in which the purchase is happening
*/
function _preValidatePurchase(address _contributor, uint256 _contributionAmount, uint _round)
internal view
{
require(_contributor != address(0));
require(currentIcoRound > 0 && currentIcoRound < 4);
require(_round > 0 && _round < 4);
require(contributions[_contributor] == 0);
require(_contributionAmount >= icoRounds[_round].individualFloor);
require(_contributionAmount < icoRounds[_round].individualCap);
require(_doesNotExceedHardCap(_contributionAmount, _round));
}
/**
* @dev define the way in which ether is converted to tokens.
* @param _contributionAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _contributionAmount
*/
function _getTokenAmount(uint256 _contributionAmount, uint256 _round)
internal view returns(uint256)
{
uint256 _rate = icoRounds[_round].rate;
return _contributionAmount.mul(_rate);
}
/**
* @dev Checks if current round hardcap will not be exceeded by a new contribution
* @param _contributionAmount purchase amount in Wei
* @param _round Round in which the purchase is happening
* @return true when current hardcap is not exceeded, false if exceeded
*/
function _doesNotExceedHardCap(uint _contributionAmount, uint _round)
internal view returns(bool)
{
uint roundHardCap = icoRounds[_round].hardCap;
return totalContributionAmount.add(_contributionAmount) <= roundHardCap;
}
/**
* @dev Function to burn unsold tokens
*/
function _burnUnsoldTokens()
internal
{
uint256 tokensToBurn = TOKENSFORSALE.sub(vestedTokens).sub(distributedTokens);
_token.burn(tokensToBurn);
}
/**
* @dev Transfer the unsold tokens to the funds collecting address
*/
function _withdrawUnsoldTokens()
internal {
uint256 tokensToWithdraw = TOKENSFORSALE.sub(vestedTokens).sub(distributedTokens);
_token.transfer(_wallet, tokensToWithdraw);
}
} | Adds list of address to whitelist. Not overloaded due to limitations with truffle testing. _beneficiary Address to be added to the whitelist/ | function addToWhitelist(address _beneficiary) public onlyOwner {
whitelist[_beneficiary] = true;
emit AddedBeneficiary(_beneficiary);
}
| 12,543,384 |
./partial_match/4/0x6b0787A77c11458EF87Bd733a63BBC11980d285D/sources/OroNetwork.sol | Emergency Withdraw Admin call/ | function emergencyWithdraw(address account, address token)
public
onlyOwner
returns (bool)
{
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(account, balance);
}
| 8,638,062 |
/**
*Submitted for verification at Etherscan.io on 2021-06-03
*/
// SPDX-License-Identifier: MIT
// Sources flattened with hardhat v2.0.5 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
pragma solidity >=0.6.0 <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
);
}
// File @openzeppelin/contracts-upgradeable/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance =
token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance =
token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data)
private
{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File contracts/interface/IInterestRateModelInterface.sol
pragma solidity 0.6.12;
/**
* @title dForce Lending Protocol's InterestRateModel Interface.
* @author dForce Team.
*/
interface IInterestRateModelInterface {
function isInterestRateModel() external view returns (bool);
/**
* @dev 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.
* @param reserves The total amnount of reserves the market has.
* @return The borrow rate per block (as a percentage, and scaled by 1e18).
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @dev 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.
* @param reserves The total amnount of reserves the market has.
* @param reserveRatio The current reserve factor the market has.
* @return The supply rate per block (as a percentage, and scaled by 1e18).
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveRatio
) external view returns (uint256);
}
// File contracts/interface/IControllerInterface.sol
pragma solidity 0.6.12;
interface IControllerAdminInterface {
/// @notice Emitted when an admin supports a market
event MarketAdded(
address iToken,
uint256 collateralFactor,
uint256 borrowFactor,
uint256 supplyCapacity,
uint256 borrowCapacity,
uint256 distributionFactor
);
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external;
/// @notice Emitted when new price oracle is set
event NewPriceOracle(address oldPriceOracle, address newPriceOracle);
function _setPriceOracle(address newOracle) external;
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(
uint256 oldCloseFactorMantissa,
uint256 newCloseFactorMantissa
);
function _setCloseFactor(uint256 newCloseFactorMantissa) external;
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(
uint256 oldLiquidationIncentiveMantissa,
uint256 newLiquidationIncentiveMantissa
);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external;
/// @notice Emitted when iToken's collateral factor is changed by admin
event NewCollateralFactor(
address iToken,
uint256 oldCollateralFactorMantissa,
uint256 newCollateralFactorMantissa
);
function _setCollateralFactor(
address iToken,
uint256 newCollateralFactorMantissa
) external;
/// @notice Emitted when iToken's borrow factor is changed by admin
event NewBorrowFactor(
address iToken,
uint256 oldBorrowFactorMantissa,
uint256 newBorrowFactorMantissa
);
function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa)
external;
/// @notice Emitted when iToken's borrow capacity is changed by admin
event NewBorrowCapacity(
address iToken,
uint256 oldBorrowCapacity,
uint256 newBorrowCapacity
);
function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity)
external;
/// @notice Emitted when iToken's supply capacity is changed by admin
event NewSupplyCapacity(
address iToken,
uint256 oldSupplyCapacity,
uint256 newSupplyCapacity
);
function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity)
external;
/// @notice Emitted when pause guardian is changed by admin
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
function _setPauseGuardian(address newPauseGuardian) external;
/// @notice Emitted when mint is paused/unpaused by admin or pause guardian
event MintPaused(address iToken, bool paused);
function _setMintPaused(address iToken, bool paused) external;
function _setAllMintPaused(bool paused) external;
/// @notice Emitted when redeem is paused/unpaused by admin or pause guardian
event RedeemPaused(address iToken, bool paused);
function _setRedeemPaused(address iToken, bool paused) external;
function _setAllRedeemPaused(bool paused) external;
/// @notice Emitted when borrow is paused/unpaused by admin or pause guardian
event BorrowPaused(address iToken, bool paused);
function _setBorrowPaused(address iToken, bool paused) external;
function _setAllBorrowPaused(bool paused) external;
/// @notice Emitted when transfer is paused/unpaused by admin or pause guardian
event TransferPaused(bool paused);
function _setTransferPaused(bool paused) external;
/// @notice Emitted when seize is paused/unpaused by admin or pause guardian
event SeizePaused(bool paused);
function _setSeizePaused(bool paused) external;
function _setiTokenPaused(address iToken, bool paused) external;
function _setProtocolPaused(bool paused) external;
event NewRewardDistributor(
address oldRewardDistributor,
address _newRewardDistributor
);
function _setRewardDistributor(address _newRewardDistributor) external;
}
interface IControllerPolicyInterface {
function beforeMint(
address iToken,
address account,
uint256 mintAmount
) external;
function afterMint(
address iToken,
address minter,
uint256 mintAmount,
uint256 mintedAmount
) external;
function beforeRedeem(
address iToken,
address redeemer,
uint256 redeemAmount
) external;
function afterRedeem(
address iToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemedAmount
) external;
function beforeBorrow(
address iToken,
address borrower,
uint256 borrowAmount
) external;
function afterBorrow(
address iToken,
address borrower,
uint256 borrowedAmount
) external;
function beforeRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function afterRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function beforeLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external;
function afterLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repaidAmount,
uint256 seizedAmount
) external;
function beforeSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizeAmount
) external;
function afterSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizedAmount
) external;
function beforeTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function afterTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function beforeFlashloan(
address iToken,
address to,
uint256 amount
) external;
function afterFlashloan(
address iToken,
address to,
uint256 amount
) external;
}
interface IControllerAccountEquityInterface {
function calcAccountEquity(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function liquidateCalculateSeizeTokens(
address iTokenBorrowed,
address iTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256);
}
interface IControllerAccountInterface {
function hasEnteredMarket(address account, address iToken)
external
view
returns (bool);
function getEnteredMarkets(address account)
external
view
returns (address[] memory);
/// @notice Emitted when an account enters a market
event MarketEntered(address iToken, address account);
function enterMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
/// @notice Emitted when an account exits a market
event MarketExited(address iToken, address account);
function exitMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
/// @notice Emitted when an account add a borrow asset
event BorrowedAdded(address iToken, address account);
/// @notice Emitted when an account remove a borrow asset
event BorrowedRemoved(address iToken, address account);
function hasBorrowed(address account, address iToken)
external
view
returns (bool);
function getBorrowedAssets(address account)
external
view
returns (address[] memory);
}
interface IControllerInterface is
IControllerAdminInterface,
IControllerPolicyInterface,
IControllerAccountEquityInterface,
IControllerAccountInterface
{
/**
* @notice Security checks when updating the comptroller of a market, always expect to return true.
*/
function isController() external view returns (bool);
/**
* @notice Return all of the iTokens
* @return The list of iToken addresses
*/
function getAlliTokens() external view returns (address[] memory);
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) external view returns (bool);
}
// File contracts/interface/IiToken.sol
pragma solidity 0.6.12;
interface IiToken {
function isSupported() external returns (bool);
function isiToken() external returns (bool);
//----------------------------------
//********* User Interface *********
//----------------------------------
function mint(address recipient, uint256 mintAmount) external;
function redeem(address from, uint256 redeemTokens) external;
function redeemUnderlying(address from, uint256 redeemAmount) external;
function borrow(uint256 borrowAmount) external;
function repayBorrow(uint256 repayAmount) external;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external;
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address iTokenCollateral
) external;
function flashloan(
address recipient,
uint256 loanAmount,
bytes memory data
) external;
function seize(
address _liquidator,
address _borrower,
uint256 _seizeTokens
) external;
function updateInterest() external returns (bool);
function controller() external view returns (address);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function totalBorrows() external view returns (uint256);
function borrowBalanceCurrent(address _user) external returns (uint256);
function borrowBalanceStored(address _user) external view returns (uint256);
function borrowIndex() external view returns (uint256);
function getAccountSnapshot(address _account)
external
view
returns (
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function getCash() external view returns (uint256);
//----------------------------------
//********* Owner Actions **********
//----------------------------------
function _setNewReserveRatio(uint256 _newReserveRatio) external;
function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external;
function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external;
function _setController(IControllerInterface _newController) external;
function _setInterestRateModel(
IInterestRateModelInterface _newInterestRateModel
) external;
function _withdrawReserves(uint256 _withdrawAmount) external;
}
// File contracts/interface/IRewardDistributorV3.sol
pragma solidity 0.6.12;
interface IRewardDistributorV3 {
function _setRewardToken(address newRewardToken) external;
/// @notice Emitted reward token address is changed by admin
event NewRewardToken(address oldRewardToken, address newRewardToken);
function _addRecipient(address _iToken, uint256 _distributionFactor)
external;
event NewRecipient(address iToken, uint256 distributionFactor);
/// @notice Emitted when mint is paused/unpaused by admin
event Paused(bool paused);
function _pause() external;
function _unpause(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external;
/// @notice Emitted when Global Distribution speed for both supply and borrow are updated
event GlobalDistributionSpeedsUpdated(
uint256 borrowSpeed,
uint256 supplySpeed
);
/// @notice Emitted when iToken's Distribution borrow speed is updated
event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed);
/// @notice Emitted when iToken's Distribution supply speed is updated
event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed);
/// @notice Emitted when iToken's Distribution factor is changed by admin
event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external;
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) external;
function claimReward(address[] memory _holders, address[] memory _iTokens)
external;
function claimAllReward(address[] memory _holders) external;
/// @notice Emitted when reward of amount is distributed into account
event RewardDistributed(
address iToken,
address account,
uint256 amount,
uint256 accountIndex
);
}
// File contracts/interface/IPriceOracle.sol
pragma solidity 0.6.12;
interface IPriceOracle {
/**
* @notice Get the underlying price of a iToken asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(address _iToken)
external
view
returns (uint256);
/**
* @notice Get the price of a underlying asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable and whether the price is valid.
*/
function getUnderlyingPriceAndStatus(address _iToken)
external
view
returns (uint256, bool);
}
// File contracts/library/Initializable.sol
pragma solidity 0.6.12;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
!_initialized,
"Initializable: contract is already initialized"
);
_;
_initialized = true;
}
}
// File contracts/library/Ownable.sol
pragma solidity 0.6.12;
/**
* @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 {_setPendingOwner} and {_acceptOwner}.
*/
contract Ownable {
/**
* @dev Returns the address of the current owner.
*/
address payable public owner;
/**
* @dev Returns the address of the current pending owner.
*/
address payable public pendingOwner;
event NewOwner(address indexed previousOwner, address indexed newOwner);
event NewPendingOwner(
address indexed oldPendingOwner,
address indexed newPendingOwner
);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "onlyOwner: caller is not the owner");
_;
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal {
owner = msg.sender;
emit NewOwner(address(0), msg.sender);
}
/**
* @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason.
* @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer.
* @param newPendingOwner New pending owner.
*/
function _setPendingOwner(address payable newPendingOwner)
external
onlyOwner
{
require(
newPendingOwner != address(0) && newPendingOwner != pendingOwner,
"_setPendingOwner: New owenr can not be zero address and owner has been set!"
);
// Gets current owner.
address oldPendingOwner = pendingOwner;
// Sets new pending owner.
pendingOwner = newPendingOwner;
emit NewPendingOwner(oldPendingOwner, newPendingOwner);
}
/**
* @dev Accepts the admin rights, but only for pendingOwenr.
*/
function _acceptOwner() external {
require(
msg.sender == pendingOwner,
"_acceptOwner: Only for pending owner!"
);
// Gets current values for events.
address oldOwner = owner;
address oldPendingOwner = pendingOwner;
// Set the new contract owner.
owner = pendingOwner;
// Clear the pendingOwner.
pendingOwner = address(0);
emit NewOwner(oldOwner, owner);
emit NewPendingOwner(oldPendingOwner, pendingOwner);
}
uint256[50] private __gap;
}
// File contracts/library/SafeRatioMath.sol
pragma solidity 0.6.12;
library SafeRatioMath {
using SafeMathUpgradeable for uint256;
uint256 private constant BASE = 10**18;
uint256 private constant DOUBLE = 10**36;
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.add(y.sub(1)).div(y);
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(y).div(BASE);
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).div(y);
}
function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).add(y.sub(1)).div(y);
}
function tmul(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256 result) {
result = x.mul(y).mul(z).div(DOUBLE);
}
function rpow(
uint256 x,
uint256 n,
uint256 base
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(
iszero(iszero(x)),
iszero(eq(div(zx, x), z))
) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
"EnumerableSet: index out of bounds"
);
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// File contracts/interface/IRewardDistributor.sol
pragma solidity 0.6.12;
interface IRewardDistributor {
function _setRewardToken(address newRewardToken) external;
/// @notice Emitted reward token address is changed by admin
event NewRewardToken(address oldRewardToken, address newRewardToken);
function _addRecipient(address _iToken, uint256 _distributionFactor)
external;
event NewRecipient(address iToken, uint256 distributionFactor);
/// @notice Emitted when mint is paused/unpaused by admin
event Paused(bool paused);
function _pause() external;
function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external;
/// @notice Emitted when Global Distribution speed for both supply and borrow are updated
event GlobalDistributionSpeedsUpdated(
uint256 borrowSpeed,
uint256 supplySpeed
);
function _setGlobalDistributionSpeeds(
uint256 borrowSpeed,
uint256 supplySpeed
) external;
/// @notice Emitted when iToken's Distribution speed is updated
event DistributionSpeedsUpdated(
address iToken,
uint256 borrowSpeed,
uint256 supplySpeed
);
function updateDistributionSpeed() external;
/// @notice Emitted when iToken's Distribution factor is changed by admin
event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function _setDistributionFactors(
address[] calldata iToken,
uint256[] calldata distributionFactors
) external;
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external;
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) external;
function claimReward(address[] memory _holders, address[] memory _iTokens)
external;
function claimAllReward(address[] memory _holders) external;
/// @notice Emitted when reward of amount is distributed into account
event RewardDistributed(
address iToken,
address account,
uint256 amount,
uint256 accountIndex
);
}
// File contracts/Controller.sol
pragma solidity 0.6.12;
/**
* @title dForce's lending controller Contract
* @author dForce
*/
contract Controller is Initializable, Ownable, IControllerInterface {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev EnumerableSet of all iTokens
EnumerableSetUpgradeable.AddressSet internal iTokens;
struct Market {
/*
* 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 in [0, 0.9], and stored as a mantissa.
*/
uint256 collateralFactorMantissa;
/*
* Multiplier representing the most one can borrow the asset.
* For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor.
* When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value
* Must be between (0, 1], and stored as a mantissa.
*/
uint256 borrowFactorMantissa;
/*
* The borrow capacity of the asset, will be checked in beforeBorrow()
* -1 means there is no limit on the capacity
* 0 means the asset can not be borrowed any more
*/
uint256 borrowCapacity;
/*
* The supply capacity of the asset, will be checked in beforeMint()
* -1 means there is no limit on the capacity
* 0 means the asset can not be supplied any more
*/
uint256 supplyCapacity;
// Whether market's mint is paused
bool mintPaused;
// Whether market's redeem is paused
bool redeemPaused;
// Whether market's borrow is paused
bool borrowPaused;
}
/// @notice Mapping of iTokens to corresponding markets
mapping(address => Market) public markets;
struct AccountData {
// Account's collateral assets
EnumerableSetUpgradeable.AddressSet collaterals;
// Account's borrowed assets
EnumerableSetUpgradeable.AddressSet borrowed;
}
/// @dev Mapping of accounts' data, including collateral and borrowed assets
mapping(address => AccountData) internal accountsData;
/**
* @notice Oracle to query the price of a given asset
*/
address public priceOracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
// closeFactorMantissa must be strictly greater than this value
uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
// liquidationIncentiveMantissa must be no less than this value
uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// collateralFactorMantissa must not exceed this value
uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0
// borrowFactorMantissa must not exceed this value
uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0
/**
* @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency
*/
address public pauseGuardian;
/// @notice whether global transfer is paused
bool public transferPaused;
/// @notice whether global seize is paused
bool public seizePaused;
/**
* @notice the address of reward distributor
*/
address public rewardDistributor;
/**
* @dev Check if called by owner or pauseGuardian, and only owner can unpause
*/
modifier checkPauser(bool _paused) {
require(
msg.sender == owner || (msg.sender == pauseGuardian && _paused),
"Only owner and guardian can pause and only owner can unpause"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize() external initializer {
__Ownable_init();
}
/*********************************/
/******** Security Check *********/
/*********************************/
/**
* @notice Ensure this is a Controller contract.
*/
function isController() external view override returns (bool) {
return true;
}
/*********************************/
/******** Admin Operations *******/
/*********************************/
/**
* @notice Admin function to add iToken into supported markets
* Checks if the iToken already exsits
* Will `revert()` if any check fails
* @param _iToken The _iToken to add
* @param _collateralFactor The _collateralFactor of _iToken
* @param _borrowFactor The _borrowFactor of _iToken
* @param _supplyCapacity The _supplyCapacity of _iToken
* @param _distributionFactor The _distributionFactor of _iToken
*/
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external override onlyOwner {
require(IiToken(_iToken).isSupported(), "Token is not supported");
// Market must not have been listed, EnumerableSet.add() will return false if it exsits
require(iTokens.add(_iToken), "Token has already been listed");
require(
_collateralFactor <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
require(
_borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Underlying price is unavailable"
);
markets[_iToken] = Market({
collateralFactorMantissa: _collateralFactor,
borrowFactorMantissa: _borrowFactor,
borrowCapacity: _borrowCapacity,
supplyCapacity: _supplyCapacity,
mintPaused: false,
redeemPaused: false,
borrowPaused: false
});
IRewardDistributor(rewardDistributor)._addRecipient(
_iToken,
_distributionFactor
);
emit MarketAdded(
_iToken,
_collateralFactor,
_borrowFactor,
_supplyCapacity,
_borrowCapacity,
_distributionFactor
);
}
/**
* @notice Sets price oracle
* @dev Admin function to set price oracle
* @param _newOracle New oracle contract
*/
function _setPriceOracle(address _newOracle) external override onlyOwner {
address _oldOracle = priceOracle;
require(
_newOracle != address(0) && _newOracle != _oldOracle,
"Oracle address invalid"
);
priceOracle = _newOracle;
emit NewPriceOracle(_oldOracle, _newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param _newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint256 _newCloseFactorMantissa)
external
override
onlyOwner
{
require(
_newCloseFactorMantissa >= closeFactorMinMantissa &&
_newCloseFactorMantissa <= closeFactorMaxMantissa,
"Close factor invalid"
);
uint256 _oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = _newCloseFactorMantissa;
emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa)
external
override
onlyOwner
{
require(
_newLiquidationIncentiveMantissa >=
liquidationIncentiveMinMantissa &&
_newLiquidationIncentiveMantissa <=
liquidationIncentiveMaxMantissa,
"Liquidation incentive invalid"
);
uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(
_oldLiquidationIncentiveMantissa,
_newLiquidationIncentiveMantissa
);
}
/**
* @notice Sets the collateralFactor for a iToken
* @dev Admin function to set collateralFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(
address _iToken,
uint256 _newCollateralFactorMantissa
) external override onlyOwner {
_checkiTokenListed(_iToken);
require(
_newCollateralFactorMantissa <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set collateral factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa;
_market.collateralFactorMantissa = _newCollateralFactorMantissa;
emit NewCollateralFactor(
_iToken,
_oldCollateralFactorMantissa,
_newCollateralFactorMantissa
);
}
/**
* @notice Sets the borrowFactor for a iToken
* @dev Admin function to set borrowFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18
*/
function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
require(
_newBorrowFactorMantissa > 0 &&
_newBorrowFactorMantissa <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set borrow factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa;
_market.borrowFactorMantissa = _newBorrowFactorMantissa;
emit NewBorrowFactor(
_iToken,
_oldBorrowFactorMantissa,
_newBorrowFactorMantissa
);
}
/**
* @notice Sets the borrowCapacity for a iToken
* @dev Admin function to set borrowCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newBorrowCapacity The new borrow capacity
*/
function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldBorrowCapacity = _market.borrowCapacity;
_market.borrowCapacity = _newBorrowCapacity;
emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity);
}
/**
* @notice Sets the supplyCapacity for a iToken
* @dev Admin function to set supplyCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newSupplyCapacity The new supply capacity
*/
function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldSupplyCapacity = _market.supplyCapacity;
_market.supplyCapacity = _newSupplyCapacity;
emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity);
}
/**
* @notice Sets the pauseGuardian
* @dev Admin function to set pauseGuardian
* @param _newPauseGuardian The new pause guardian
*/
function _setPauseGuardian(address _newPauseGuardian)
external
override
onlyOwner
{
address _oldPauseGuardian = pauseGuardian;
require(
_newPauseGuardian != address(0) &&
_newPauseGuardian != _oldPauseGuardian,
"Pause guardian address invalid"
);
pauseGuardian = _newPauseGuardian;
emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian);
}
/**
* @notice pause/unpause mint() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllMintPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setMintPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause mint() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setMintPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setMintPausedInternal(_iToken, _paused);
}
function _setMintPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].mintPaused = _paused;
emit MintPaused(_iToken, _paused);
}
/**
* @notice pause/unpause redeem() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllRedeemPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setRedeemPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause redeem() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setRedeemPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setRedeemPausedInternal(_iToken, _paused);
}
function _setRedeemPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
}
/**
* @notice pause/unpause borrow() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllBorrowPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setBorrowPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause borrow() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setBorrowPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setBorrowPausedInternal(_iToken, _paused);
}
function _setBorrowPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause global transfer()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setTransferPaused(bool _paused)
external
override
checkPauser(_paused)
{
_setTransferPausedInternal(_paused);
}
function _setTransferPausedInternal(bool _paused) internal {
transferPaused = _paused;
emit TransferPaused(_paused);
}
/**
* @notice pause/unpause global seize()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setSeizePaused(bool _paused)
external
override
checkPauser(_paused)
{
_setSeizePausedInternal(_paused);
}
function _setSeizePausedInternal(bool _paused) internal {
seizePaused = _paused;
emit SeizePaused(_paused);
}
/**
* @notice pause/unpause all actions iToken, including mint/redeem/borrow
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setiTokenPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setiTokenPausedInternal(_iToken, _paused);
}
function _setiTokenPausedInternal(address _iToken, bool _paused) internal {
Market storage _market = markets[_iToken];
_market.mintPaused = _paused;
emit MintPaused(_iToken, _paused);
_market.redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
_market.borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setProtocolPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
address _iToken = _iTokens.at(i);
_setiTokenPausedInternal(_iToken, _paused);
}
_setTransferPausedInternal(_paused);
_setSeizePausedInternal(_paused);
}
/**
* @notice Sets Reward Distributor
* @dev Admin function to set reward distributor
* @param _newRewardDistributor new reward distributor
*/
function _setRewardDistributor(address _newRewardDistributor)
external
override
onlyOwner
{
address _oldRewardDistributor = rewardDistributor;
require(
_newRewardDistributor != address(0) &&
_newRewardDistributor != _oldRewardDistributor,
"Reward Distributor address invalid"
);
rewardDistributor = _newRewardDistributor;
emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor);
}
/*********************************/
/******** Poclicy Hooks **********/
/*********************************/
/**
* @notice Hook function before iToken `mint()`
* Checks if the account should be allowed to mint the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the mint against
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
*/
function beforeMint(
address _iToken,
address _minter,
uint256 _mintAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.mintPaused, "Token mint has been paused");
// Check the iToken's supply capacity, -1 means no limit
uint256 _totalSupplyUnderlying =
IERC20Upgradeable(_iToken).totalSupply().rmul(
IiToken(_iToken).exchangeRateStored()
);
require(
_totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity,
"Token supply capacity reached"
);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_minter,
false
);
}
/**
* @notice Hook function after iToken `mint()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being minted
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
* @param _mintedAmount The amount of iToken being minted
*/
function afterMint(
address _iToken,
address _minter,
uint256 _mintAmount,
uint256 _mintedAmount
) external override {
_iToken;
_minter;
_mintAmount;
_mintedAmount;
}
/**
* @notice Hook function before iToken `redeem()`
* Checks if the account should be allowed to redeem the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the redeem against
* @param _redeemer The account which would redeem iToken
* @param _redeemAmount The amount of iToken to redeem
*/
function beforeRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!markets[_iToken].redeemPaused, "Token redeem has been paused");
_redeemAllowed(_iToken, _redeemer, _redeemAmount);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_redeemer,
false
);
}
/**
* @notice Hook function after iToken `redeem()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being redeemed
* @param _redeemer The account which redeemed iToken
* @param _redeemAmount The amount of iToken being redeemed
* @param _redeemedUnderlying The amount of underlying being redeemed
*/
function afterRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount,
uint256 _redeemedUnderlying
) external override {
_iToken;
_redeemer;
_redeemAmount;
_redeemedUnderlying;
}
/**
* @notice Hook function before iToken `borrow()`
* Checks if the account should be allowed to borrow the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the borrow against
* @param _borrower The account which would borrow iToken
* @param _borrowAmount The amount of underlying to borrow
*/
function beforeBorrow(
address _iToken,
address _borrower,
uint256 _borrowAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.borrowPaused, "Token borrow has been paused");
if (!hasBorrowed(_borrower, _iToken)) {
// Unlike collaterals, borrowed asset can only be added by iToken,
// rather than enabled by user directly.
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just add it
_addToBorrowed(_borrower, _iToken);
}
// Check borrower's equity
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount);
require(_shortfall == 0, "Account has some shortfall");
// Check the iToken's borrow capacity, -1 means no limit
uint256 _totalBorrows = IiToken(_iToken).totalBorrows();
require(
_totalBorrows.add(_borrowAmount) <= _market.borrowCapacity,
"Token borrow capacity reached"
);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
}
/**
* @notice Hook function after iToken `borrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being borrewd
* @param _borrower The account which borrowed iToken
* @param _borrowedAmount The amount of underlying being borrowed
*/
function afterBorrow(
address _iToken,
address _borrower,
uint256 _borrowedAmount
) external override {
_iToken;
_borrower;
_borrowedAmount;
}
/**
* @notice Hook function before iToken `repayBorrow()`
* Checks if the account should be allowed to repay the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iToken The iToken to verify the repay against
* @param _payer The account which would repay iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
_payer;
_repayAmount;
}
/**
* @notice Hook function after iToken `repayBorrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being repaid
* @param _payer The account which would repay
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying being repaied
*/
function afterRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Remove _iToken from borrowed list if new borrow balance is 0
if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) {
// Only allow called by iToken as we are going to remove this token from borrower's borrowed list
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just remove it
_removeFromBorrowed(_borrower, _iToken);
}
_payer;
_repayAmount;
}
/**
* @notice Hook function before iToken `liquidateBorrow()`
* Checks if the account should be allowed to liquidate the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be liqudate with
* @param _liquidator The account which would repay the borrowed iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repayAmount
) external override {
// Tokens must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
(, uint256 _shortfall, , ) = calcAccountEquity(_borrower);
require(_shortfall > 0, "Account does not have shortfall");
// Only allowed to repay the borrow balance's close factor
uint256 _borrowBalance =
IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower);
uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa);
require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed");
_liquidator;
}
/**
* @notice Hook function after iToken `liquidateBorrow()`
* Will `revert()` if any operation fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _liquidator The account which would repay and seize
* @param _borrower The account which has borrowed
* @param _repaidAmount The amount of underlying being repaied
* @param _seizedAmount The amount of collateral being seized
*/
function afterLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repaidAmount,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_repaidAmount;
_seizedAmount;
// Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance
// No need to check whether should remove from borrowed asset list
}
/**
* @notice Hook function before iToken `seize()`
* Checks if the liquidator should be allowed to seize the collateral iToken
* Will `revert()` if any check fails
* @param _iTokenCollateral The collateral iToken to be seize
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid the borrowed iToken
* @param _borrower The account which has borrowed
* @param _seizeAmount The amount of collateral iToken to seize
*/
function beforeSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizeAmount
) external override {
require(!seizePaused, "Seize has been paused");
// Markets must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
// Sanity Check the controllers
require(
IiToken(_iTokenBorrowed).controller() ==
IiToken(_iTokenCollateral).controller(),
"Controller mismatch between Borrowed and Collateral"
);
// Update the Reward Distribution Supply state on collateral
IRewardDistributor(rewardDistributor).updateDistributionState(
_iTokenCollateral,
false
);
// Update reward of liquidator and borrower on collateral
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_liquidator,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_borrower,
false
);
_seizeAmount;
}
/**
* @notice Hook function after iToken `seize()`
* Will `revert()` if any operation fails
* @param _iTokenCollateral The collateral iToken to be seized
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid and seized
* @param _borrower The account which has borrowed
* @param _seizedAmount The amount of collateral being seized
*/
function afterSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_seizedAmount;
}
/**
* @notice Hook function before iToken `transfer()`
* Checks if the transfer should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be transfered
* @param _from The account to be transfered from
* @param _to The account to be transfered to
* @param _amount The amount to be transfered
*/
function beforeTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!transferPaused, "Transfer has been paused");
// Check account equity with this amount to decide whether the transfer is allowed
_redeemAllowed(_iToken, _from, _amount);
// Update the Reward Distribution supply state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
// Update reward of from and to
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_from,
false
);
IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false);
}
/**
* @notice Hook function after iToken `transfer()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was transfered
* @param _from The account was transfer from
* @param _to The account was transfer to
* @param _amount The amount was transfered
*/
function afterTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
_iToken;
_from;
_to;
_amount;
}
/**
* @notice Hook function before iToken `flashloan()`
* Checks if the flashloan should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be flashloaned
* @param _to The account flashloaned transfer to
* @param _amount The amount to be flashloaned
*/
function beforeFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
// Flashloan share the same pause state with borrow
require(!markets[_iToken].borrowPaused, "Token borrow has been paused");
_checkiTokenListed(_iToken);
_to;
_amount;
// Update the Reward Distribution Borrow state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
}
/**
* @notice Hook function after iToken `flashloan()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was flashloaned
* @param _to The account flashloan transfer to
* @param _amount The amount was flashloaned
*/
function afterFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
_iToken;
_to;
_amount;
}
/*********************************/
/***** Internal Functions *******/
/*********************************/
function _redeemAllowed(
address _iToken,
address _redeemer,
uint256 _amount
) private view {
_checkiTokenListed(_iToken);
// No need to check liquidity if _redeemer has not used _iToken as collateral
if (!accountsData[_redeemer].collaterals.contains(_iToken)) {
return;
}
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0);
require(_shortfall == 0, "Account has some shortfall");
}
/**
* @dev Check if _iToken is listed
*/
function _checkiTokenListed(address _iToken) private view {
require(iTokens.contains(_iToken), "Token has not been listed");
}
/*********************************/
/** Account equity calculation ***/
/*********************************/
/**
* @notice Calculates current account equity
* @param _account The account to query equity of
* @return account equity, shortfall, collateral value, borrowed value.
*/
function calcAccountEquity(address _account)
public
view
override
returns (
uint256,
uint256,
uint256,
uint256
)
{
return calcAccountEquityWithEffect(_account, address(0), 0, 0);
}
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `iTokenBalance` is the number of iTokens the account owns in the collateral,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountEquityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowed;
uint256 iTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 underlyingPrice;
uint256 collateralValue;
uint256 borrowValue;
}
/**
* @notice Calculates current account equity plus some token and amount to effect
* @param _account The account to query equity of
* @param _tokenToEffect The token address to add some additional redeeem/borrow
* @param _redeemAmount The additional amount to redeem
* @param _borrowAmount The additional amount to borrow
* @return account euqity, shortfall, collateral value, borrowed value plus the effect.
*/
function calcAccountEquityWithEffect(
address _account,
address _tokenToEffect,
uint256 _redeemAmount,
uint256 _borrowAmount
)
internal
view
virtual
returns (
uint256,
uint256,
uint256,
uint256
)
{
AccountEquityLocalVars memory _local;
AccountData storage _accountData = accountsData[_account];
// Calculate value of all collaterals
// collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor
// collateralValue = balance * collateralValuePerToken
// sumCollateral += collateralValue
uint256 _len = _accountData.collaterals.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.collaterals.at(i));
_local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf(
_account
);
_local.exchangeRateMantissa = _token.exchangeRateStored();
if (_tokenToEffect == address(_token) && _redeemAmount > 0) {
_local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
_local.collateralValue = _local
.iTokenBalance
.mul(_local.underlyingPrice)
.rmul(_local.exchangeRateMantissa)
.rmul(markets[address(_token)].collateralFactorMantissa);
_local.sumCollateral = _local.sumCollateral.add(
_local.collateralValue
);
}
// Calculate all borrowed value
// borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor
// sumBorrowed += borrowValue
_len = _accountData.borrowed.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.borrowed.at(i));
_local.borrowBalance = _token.borrowBalanceStored(_account);
if (_tokenToEffect == address(_token) && _borrowAmount > 0) {
_local.borrowBalance = _local.borrowBalance.add(_borrowAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
// borrowFactorMantissa can not be set to 0
_local.borrowValue = _local
.borrowBalance
.mul(_local.underlyingPrice)
.rdiv(markets[address(_token)].borrowFactorMantissa);
_local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue);
}
// Should never underflow
return
_local.sumCollateral > _local.sumBorrowed
? (
_local.sumCollateral - _local.sumBorrowed,
uint256(0),
_local.sumCollateral,
_local.sumBorrowed
)
: (
uint256(0),
_local.sumBorrowed - _local.sumCollateral,
_local.sumCollateral,
_local.sumBorrowed
);
}
/**
* @notice Calculate amount of collateral iToken to seize after repaying an underlying amount
* @dev Used in liquidation
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _actualRepayAmount The amount of underlying token liquidator has repaied
* @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized
*/
function liquidateCalculateSeizeTokens(
address _iTokenBorrowed,
address _iTokenCollateral,
uint256 _actualRepayAmount
) external view virtual override returns (uint256 _seizedTokenCollateral) {
/* Read oracle prices for borrowed and collateral assets */
uint256 _priceBorrowed =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed);
uint256 _priceCollateral =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral);
require(
_priceBorrowed != 0 && _priceCollateral != 0,
"Borrowed or Collateral asset price is invalid"
);
uint256 _valueRepayPlusIncentive =
_actualRepayAmount.mul(_priceBorrowed).rmul(
liquidationIncentiveMantissa
);
// Use stored value here as it is view function
uint256 _exchangeRateMantissa =
IiToken(_iTokenCollateral).exchangeRateStored();
// seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral
// valuePerTokenCollateral = exchangeRateMantissa * priceCollateral
_seizedTokenCollateral = _valueRepayPlusIncentive
.rdiv(_exchangeRateMantissa)
.div(_priceCollateral);
}
/*********************************/
/*** Account Markets Operation ***/
/*********************************/
/**
* @notice Returns the markets list the account has entered
* @param _account The address of the account to query
* @return _accountCollaterals The markets list the account has entered
*/
function getEnteredMarkets(address _account)
external
view
override
returns (address[] memory _accountCollaterals)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.collaterals.length();
_accountCollaterals = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_accountCollaterals[i] = _accountData.collaterals.at(i);
}
}
/**
* @notice Add markets to `msg.sender`'s markets list for liquidity calculations
* @param _iTokens The list of addresses of the iToken markets to be entered
* @return _results Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _enterMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Add the market to the account's markets list for liquidity calculations
* @param _iToken The market to enter
* @param _account The address of the account to modify
* @return True if entered successfully, false for non-listed market or other errors
*/
function _enterMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return false;
}
// add() will return false if iToken is in account's market list
if (accountsData[_account].collaterals.add(_iToken)) {
emit MarketEntered(_iToken, _account);
}
return true;
}
/**
* @notice Returns whether the given account has entered the market
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has entered the market, otherwise false.
*/
function hasEnteredMarket(address _account, address _iToken)
external
view
override
returns (bool)
{
return accountsData[_account].collaterals.contains(_iToken);
}
/**
* @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations
* @param _iTokens The list of addresses of the iToken to exit
* @return _results Success indicators for whether each corresponding market was exited
*/
function exitMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _exitMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Remove the market to the account's markets list for liquidity calculations
* @param _iToken The market to exit
* @param _account The address of the account to modify
* @return True if exit successfully, false for non-listed market or other errors
*/
function _exitMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return true;
}
// Account has not entered this market, skip it
if (!accountsData[_account].collaterals.contains(_iToken)) {
return true;
}
// Get the iToken balance
uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Check account's equity if all balance are redeemed
// which means iToken can be removed from collaterals
_redeemAllowed(_iToken, _account, _balance);
// Have checked account has entered market before
accountsData[_account].collaterals.remove(_iToken);
emit MarketExited(_iToken, _account);
return true;
}
/**
* @notice Returns the asset list the account has borrowed
* @param _account The address of the account to query
* @return _borrowedAssets The asset list the account has borrowed
*/
function getBorrowedAssets(address _account)
external
view
override
returns (address[] memory _borrowedAssets)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.borrowed.length();
_borrowedAssets = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_borrowedAssets[i] = _accountData.borrowed.at(i);
}
}
/**
* @notice Add the market to the account's borrowed list for equity calculations
* @param _iToken The iToken of underlying to borrow
* @param _account The address of the account to modify
*/
function _addToBorrowed(address _account, address _iToken) internal {
// add() will return false if iToken is in account's market list
if (accountsData[_account].borrowed.add(_iToken)) {
emit BorrowedAdded(_iToken, _account);
}
}
/**
* @notice Returns whether the given account has borrowed the given iToken
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has borrowed the iToken, otherwise false.
*/
function hasBorrowed(address _account, address _iToken)
public
view
override
returns (bool)
{
return accountsData[_account].borrowed.contains(_iToken);
}
/**
* @notice Remove the iToken from the account's borrowed list
* @param _iToken The iToken to remove
* @param _account The address of the account to modify
*/
function _removeFromBorrowed(address _account, address _iToken) internal {
// remove() will return false if iToken does not exist in account's borrowed list
if (accountsData[_account].borrowed.remove(_iToken)) {
emit BorrowedRemoved(_iToken, _account);
}
}
/*********************************/
/****** General Information ******/
/*********************************/
/**
* @notice Return all of the iTokens
* @return _alliTokens The list of iToken addresses
*/
function getAlliTokens()
public
view
override
returns (address[] memory _alliTokens)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
_alliTokens = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_alliTokens[i] = _iTokens.at(i);
}
}
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) public view override returns (bool) {
return iTokens.contains(_iToken);
}
}
// File contracts/RewardDistributorV3.sol
pragma solidity 0.6.12;
/**
* @title dForce's lending reward distributor Contract
* @author dForce
*/
contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 {
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice the controller
Controller public controller;
/// @notice the global Reward distribution speed
uint256 public globalDistributionSpeed;
/// @notice the Reward distribution speed of each iToken
mapping(address => uint256) public distributionSpeed;
/// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa
mapping(address => uint256) public distributionFactorMantissa;
struct DistributionState {
// Token's last updated index, stored as a mantissa
uint256 index;
// The block number the index was last updated at
uint256 block;
}
/// @notice the Reward distribution supply state of each iToken
mapping(address => DistributionState) public distributionSupplyState;
/// @notice the Reward distribution borrow state of each iToken
mapping(address => DistributionState) public distributionBorrowState;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionSupplierIndex;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionBorrowerIndex;
/// @notice the Reward distributed into each account
mapping(address => uint256) public reward;
/// @notice the Reward token address
address public rewardToken;
/// @notice whether the reward distribution is paused
bool public paused;
/// @notice the Reward distribution speed supply side of each iToken
mapping(address => uint256) public distributionSupplySpeed;
/// @notice the global Reward distribution speed for supply
uint256 public globalDistributionSupplySpeed;
/**
* @dev Throws if called by any account other than the controller.
*/
modifier onlyController() {
require(
address(controller) == msg.sender,
"onlyController: caller is not the controller"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize(Controller _controller) external initializer {
require(
address(_controller) != address(0),
"initialize: controller address should not be zero address!"
);
__Ownable_init();
controller = _controller;
paused = true;
}
/**
* @notice set reward token address
* @dev Admin function, only owner can call this
* @param _newRewardToken the address of reward token
*/
function _setRewardToken(address _newRewardToken)
external
override
onlyOwner
{
address _oldRewardToken = rewardToken;
require(
_newRewardToken != address(0) && _newRewardToken != _oldRewardToken,
"Reward token address invalid"
);
rewardToken = _newRewardToken;
emit NewRewardToken(_oldRewardToken, _newRewardToken);
}
/**
* @notice Add the iToken as receipient
* @dev Admin function, only controller can call this
* @param _iToken the iToken to add as recipient
* @param _distributionFactor the distribution factor of the recipient
*/
function _addRecipient(address _iToken, uint256 _distributionFactor)
external
override
onlyController
{
distributionFactorMantissa[_iToken] = _distributionFactor;
distributionSupplyState[_iToken] = DistributionState({
index: 0,
block: block.number
});
distributionBorrowState[_iToken] = DistributionState({
index: 0,
block: block.number
});
emit NewRecipient(_iToken, _distributionFactor);
}
/**
* @notice Pause the reward distribution
* @dev Admin function, pause will set global speed to 0 to stop the accumulation
*/
function _pause() external override onlyOwner {
// Set the global distribution speed to 0 to stop accumulation
address[] memory _iTokens = controller.getAlliTokens();
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionBorrowSpeed(_iTokens[i], 0);
_setDistributionSupplySpeed(_iTokens[i], 0);
}
_refreshGlobalDistributionSpeeds();
_setPaused(true);
}
/**
* @notice Unpause and set distribution speeds
* @dev Admin function
* @param _borrowiTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
* @param _supplyiTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _unpause(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external override onlyOwner {
_setPaused(false);
_setDistributionSpeedsInternal(
_borrowiTokens,
_borrowSpeeds,
_supplyiTokens,
_supplySpeeds
);
_refreshGlobalDistributionSpeeds();
}
/**
* @notice Pause/Unpause the reward distribution
* @dev Admin function
* @param _paused whether to pause/unpause the distribution
*/
function _setPaused(bool _paused) internal {
paused = _paused;
emit Paused(_paused);
}
/**
* @notice Set distribution speeds
* @dev Admin function, will fail when paused
* @param _borrowiTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
* @param _supplyiTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _setDistributionSpeeds(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external onlyOwner {
require(!paused, "Can not change speeds when paused");
_setDistributionSpeedsInternal(
_borrowiTokens,
_borrowSpeeds,
_supplyiTokens,
_supplySpeeds
);
_refreshGlobalDistributionSpeeds();
}
function _setDistributionSpeedsInternal(
address[] memory _borrowiTokens,
uint256[] memory _borrowSpeeds,
address[] memory _supplyiTokens,
uint256[] memory _supplySpeeds
) internal {
_setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds);
_setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds);
}
/**
* @notice Set borrow distribution speeds
* @dev Admin function, will fail when paused
* @param _iTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
*/
function _setDistributionBorrowSpeeds(
address[] calldata _iTokens,
uint256[] calldata _borrowSpeeds
) external onlyOwner {
require(!paused, "Can not change borrow speeds when paused");
_setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds);
_refreshGlobalDistributionSpeeds();
}
/**
* @notice Set supply distribution speeds
* @dev Admin function, will fail when paused
* @param _iTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _setDistributionSupplySpeeds(
address[] calldata _iTokens,
uint256[] calldata _supplySpeeds
) external onlyOwner {
require(!paused, "Can not change supply speeds when paused");
_setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds);
_refreshGlobalDistributionSpeeds();
}
function _refreshGlobalDistributionSpeeds() internal {
address[] memory _iTokens = controller.getAlliTokens();
uint256 _len = _iTokens.length;
uint256 _borrowSpeed;
uint256 _supplySpeed;
for (uint256 i = 0; i < _len; i++) {
_borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]);
_supplySpeed = _supplySpeed.add(
distributionSupplySpeed[_iTokens[i]]
);
}
globalDistributionSpeed = _borrowSpeed;
globalDistributionSupplySpeed = _supplySpeed;
emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed);
}
function _setDistributionBorrowSpeedsInternal(
address[] memory _iTokens,
uint256[] memory _borrowSpeeds
) internal {
require(
_iTokens.length == _borrowSpeeds.length,
"Length of _iTokens and _borrowSpeeds mismatch"
);
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]);
}
}
function _setDistributionSupplySpeedsInternal(
address[] memory _iTokens,
uint256[] memory _supplySpeeds
) internal {
require(
_iTokens.length == _supplySpeeds.length,
"Length of _iTokens and _supplySpeeds mismatch"
);
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]);
}
}
function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed)
internal
{
// iToken must have been listed
require(controller.hasiToken(_iToken), "Token has not been listed");
// Update borrow state before updating new speed
_updateDistributionState(_iToken, true);
distributionSpeed[_iToken] = _borrowSpeed;
emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed);
}
function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed)
internal
{
// iToken must have been listed
require(controller.hasiToken(_iToken), "Token has not been listed");
// Update supply state before updating new speed
_updateDistributionState(_iToken, false);
distributionSupplySpeed[_iToken] = _supplySpeed;
emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed);
}
/**
* @notice Update the iToken's Reward distribution state
* @dev Will be called every time when the iToken's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateDistributionState(address _iToken, bool _isBorrow)
external
override
{
// Skip all updates if it is paused
if (paused) {
return;
}
_updateDistributionState(_iToken, _isBorrow);
}
function _updateDistributionState(address _iToken, bool _isBorrow)
internal
{
require(controller.hasiToken(_iToken), "Token has not been listed");
DistributionState storage state =
_isBorrow
? distributionBorrowState[_iToken]
: distributionSupplyState[_iToken];
uint256 _speed =
_isBorrow
? distributionSpeed[_iToken]
: distributionSupplySpeed[_iToken];
uint256 _blockNumber = block.number;
uint256 _deltaBlocks = _blockNumber.sub(state.block);
if (_deltaBlocks > 0 && _speed > 0) {
uint256 _totalToken =
_isBorrow
? IiToken(_iToken).totalBorrows()
: IERC20Upgradeable(_iToken).totalSupply();
uint256 _totalDistributed = _speed.mul(_deltaBlocks);
// Reward distributed per token since last time
uint256 _distributedPerToken =
_totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0;
state.index = state.index.add(_distributedPerToken);
}
state.block = _blockNumber;
}
/**
* @notice Update the account's Reward distribution state
* @dev Will be called every time when the account's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _account The account to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external override {
// Skip all updates if it is paused
if (paused) {
return;
}
_updateReward(_iToken, _account, _isBorrow);
}
function _updateReward(
address _iToken,
address _account,
bool _isBorrow
) internal {
require(_account != address(0), "Invalid account address!");
require(controller.hasiToken(_iToken), "Token has not been listed");
uint256 _iTokenIndex;
uint256 _accountIndex;
uint256 _accountBalance;
if (_isBorrow) {
_iTokenIndex = distributionBorrowState[_iToken].index;
_accountIndex = distributionBorrowerIndex[_iToken][_account];
_accountBalance = IiToken(_iToken).borrowBalanceStored(_account);
// Update the account state to date
distributionBorrowerIndex[_iToken][_account] = _iTokenIndex;
} else {
_iTokenIndex = distributionSupplyState[_iToken].index;
_accountIndex = distributionSupplierIndex[_iToken][_account];
_accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Update the account state to date
distributionSupplierIndex[_iToken][_account] = _iTokenIndex;
}
uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex);
uint256 _amount = _accountBalance.rmul(_deltaIndex);
if (_amount > 0) {
reward[_account] = reward[_account].add(_amount);
emit RewardDistributed(_iToken, _account, _amount, _accountIndex);
}
}
/**
* @notice Update reward accrued in iTokens by the holders regardless of paused or not
* @param _holders The account to update
* @param _iTokens The _iTokens to update
*/
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) public override {
// Update rewards for all _iTokens for holders
for (uint256 i = 0; i < _iTokens.length; i++) {
address _iToken = _iTokens[i];
_updateDistributionState(_iToken, false);
_updateDistributionState(_iToken, true);
for (uint256 j = 0; j < _holders.length; j++) {
_updateReward(_iToken, _holders[j], false);
_updateReward(_iToken, _holders[j], true);
}
}
}
/**
* @notice Claim reward accrued in iTokens by the holders
* @param _holders The account to claim for
* @param _iTokens The _iTokens to claim from
*/
function claimReward(address[] memory _holders, address[] memory _iTokens)
public
override
{
updateRewardBatch(_holders, _iTokens);
// Withdraw all reward for all holders
for (uint256 j = 0; j < _holders.length; j++) {
address _account = _holders[j];
uint256 _reward = reward[_account];
if (_reward > 0) {
reward[_account] = 0;
IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward);
}
}
}
/**
* @notice Claim reward accrued in all iTokens by the holders
* @param _holders The account to claim for
*/
function claimAllReward(address[] memory _holders) external override {
claimReward(_holders, controller.getAlliTokens());
}
} | ---------------------------------- User Interface -------------------------------------------------------------------- Owner Actions ---------------------------------- | interface IiToken {
function isSupported() external returns (bool);
function isiToken() external returns (bool);
function mint(address recipient, uint256 mintAmount) external;
function redeem(address from, uint256 redeemTokens) external;
function redeemUnderlying(address from, uint256 redeemAmount) external;
function borrow(uint256 borrowAmount) external;
function repayBorrow(uint256 repayAmount) external;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external;
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address iTokenCollateral
) external;
function flashloan(
address recipient,
uint256 loanAmount,
bytes memory data
) external;
function seize(
address _liquidator,
address _borrower,
uint256 _seizeTokens
) external;
function updateInterest() external returns (bool);
function controller() external view returns (address);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function totalBorrows() external view returns (uint256);
function borrowBalanceCurrent(address _user) external returns (uint256);
function borrowBalanceStored(address _user) external view returns (uint256);
function borrowIndex() external view returns (uint256);
function getAccountSnapshot(address _account)
external
view
returns (
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function getCash() external view returns (uint256);
function _setNewReserveRatio(uint256 _newReserveRatio) external;
function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external;
function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external;
function _setController(IControllerInterface _newController) external;
function _setInterestRateModel(
IInterestRateModelInterface _newInterestRateModel
) external;
function _withdrawReserves(uint256 _withdrawAmount) external;
}
}
| 2,030,153 |
pragma solidity ^0.6.1;
pragma experimental ABIEncoderV2;
import "./IPoTypes.sol";
interface IPurchasing
{
//---------------------------------------------------------
// Events
//---------------------------------------------------------
// Events Header level
event PurchaseOrderCreateRequestLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.Po po);
event PurchaseOrderCreatedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.Po po);
event PurchaseOrderNotCreatedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.Po po);
// Events Item level (matching 1:1 with PoItemStatus)
event PurchaseItemAcceptedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemRejectedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemReadyForGoodsIssueLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemGoodsIssuedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemReceivedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemCompletedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemCancelledLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
// Events Item level (for escrow release)
event PurchaseItemEscrowReleasedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemEscrowFailedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
//---------------------------------------------------------
// Functions
//---------------------------------------------------------
// Contract setup
function configure(string calldata nameOfPoStorage, string calldata nameOfBusinessPartnerStorage, string calldata nameOfFunding) external;
// Purchasing
function getPo(uint poNumber) external view returns (IPoTypes.Po memory po);
function getPoBySellerAndQuote(string calldata sellerIdString, uint quoteId) external view returns (IPoTypes.Po memory po);
// Only from Buyer Wallet
function createPurchaseOrder(IPoTypes.Po calldata po) external;
function cancelPurchaseOrderItem(uint poNumber, uint8 poItemNumber) external;
function setPoItemGoodsReceivedBuyer(uint poNumber, uint8 poItemNumber) external;
// Only from Seller Wallet
function setPoItemAccepted(uint poNumber, uint8 poItemNumber, bytes32 soNumber, bytes32 soItemNumber) external;
function setPoItemRejected(uint poNumber, uint8 poItemNumber) external;
function setPoItemReadyForGoodsIssue(uint poNumber, uint8 poItemNumber) external;
function setPoItemGoodsIssued(uint poNumber, uint8 poItemNumber) external;
function setPoItemGoodsReceivedSeller(uint poNumber, uint8 poItemNumber) external;
} | --------------------------------------------------------- Events--------------------------------------------------------- Events Header level Events Item level (matching 1:1 with PoItemStatus) Events Item level (for escrow release)--------------------------------------------------------- Functions--------------------------------------------------------- Contract setup Purchasing Only from Buyer Wallet Only from Seller Wallet | {
event PurchaseOrderCreateRequestLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.Po po);
event PurchaseOrderCreatedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.Po po);
event PurchaseOrderNotCreatedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.Po po);
event PurchaseItemAcceptedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemRejectedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemReadyForGoodsIssueLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemGoodsIssuedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemReceivedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemCompletedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemCancelledLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemEscrowReleasedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
event PurchaseItemEscrowFailedLog(address indexed buyerAddress, bytes32 indexed sellerId, uint indexed poNumber, IPoTypes.PoItem poItem);
function configure(string calldata nameOfPoStorage, string calldata nameOfBusinessPartnerStorage, string calldata nameOfFunding) external;
function getPo(uint poNumber) external view returns (IPoTypes.Po memory po);
function getPoBySellerAndQuote(string calldata sellerIdString, uint quoteId) external view returns (IPoTypes.Po memory po);
function createPurchaseOrder(IPoTypes.Po calldata po) external;
function cancelPurchaseOrderItem(uint poNumber, uint8 poItemNumber) external;
function setPoItemGoodsReceivedBuyer(uint poNumber, uint8 poItemNumber) external;
function setPoItemAccepted(uint poNumber, uint8 poItemNumber, bytes32 soNumber, bytes32 soItemNumber) external;
function setPoItemRejected(uint poNumber, uint8 poItemNumber) external;
function setPoItemReadyForGoodsIssue(uint poNumber, uint8 poItemNumber) external;
function setPoItemGoodsIssued(uint poNumber, uint8 poItemNumber) external;
function setPoItemGoodsReceivedSeller(uint poNumber, uint8 poItemNumber) external;
} | 6,449,236 |
./full_match/97/0x960f3698eAF064c3D6e1A13F9B1e445D799dd122/sources/project:/contracts/NFT.sol | MINT NFT(ERC721) ACCOUNT BALANCE SHOULD MORE THAN MINT PRICE | function mintNFT(
string memory getURI,
uint price,
bytes32 encryptHashValue
) external {
require(actualSale == true, "Sale Off");
setHash(price);
bool checkHash = getHashValue(encryptHashValue);
require(checkHash == true, "Invalid Transfer Hash");
uint256 balance = IERC20(SPALAddress).balanceOf(msg.sender);
uint256 mintPrice = price;
uint8 rarity = 0;
uint getrarity = uint(
keccak256(
abi.encodePacked(block.timestamp, block.difficulty, msg.sender)
)
) % 100;
if (getrarity < 1) {
rarity = 1;
rarity = 2;
rarity = 3;
rarity = 4;
rarity = 5;
revert("Error in getting rarity");
}
(bool checkMint, ) = countMintFunction();
if (checkMint) {
require((balance > mintPrice), "Insufficient Balance");
IERC20(SPALAddress).transferFrom(
msg.sender,
CompanyAddress,
mintPrice
);
_safeMint(msg.sender, NFTId);
_tokenDetails[NFTId] = NFTS(
NFTId,
0,
rarity,
1,
"",
block.timestamp,
block.timestamp,
false,
false
);
_countMint[msg.sender].push(block.timestamp);
_setTokenURI(NFTId, getURI);
NFTId++;
revert("One account only allow 5 mint per day");
}
emit MintEvent(
(NFTId - 1),
msg.sender,
0,
rarity,
1,
getURI,
block.timestamp,
block.timestamp,
false,
false
);
}
| 3,294,768 |
pragma solidity ^0.5.8;
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
/// @title zkSync main contract
/// @author Matter Labs
contract ZkSync is UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32
public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
function upgradeNoticePeriodStarted() external {}
/// @notice Notification that upgrade preparation status is activated
function upgradePreparationStarted() external {
upgradePreparationActive = true;
upgradePreparationActivationTime = now;
}
/// @notice Notification that upgrade canceled
function upgradeCanceled() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
function upgradeFinishes() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool) {
return !exodusMode;
}
/// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _governanceAddress The address of Governance contract
/// _verifierAddress The address of Verifier contract
/// _ // FIXME: remove _genesisAccAddress
/// _genesisRoot Genesis blocks (first block) root
function initialize(bytes calldata initializationParameters) external {
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
bytes32 _genesisRoot
) = abi.decode(initializationParameters, (address, address, bytes32));
verifier = Verifier(_verifierAddress);
governance = Governance(_governanceAddress);
blocks[0].stateRoot = _genesisRoot;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Sends tokens
/// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @param _maxAmount Maximum possible amount of tokens to transfer to this account
function withdrawERC20Guarded(
IERC20 _token,
address _to,
uint128 _amount,
uint128 _maxAmount
) external returns (uint128 withdrawnAmount) {
require(msg.sender == address(this), "wtg10"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed)
uint256 balance_before = _token.balanceOf(address(this));
require(Utils.sendERC20(_token, _to, _amount), "wtg11"); // wtg11 - ERC20 transfer fails
uint256 balance_after = _token.balanceOf(address(this));
uint256 balance_diff = balance_before.sub(balance_after);
require(balance_diff <= _maxAmount, "wtg12"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount
return SafeCast.toUint128(balance_diff);
}
/// @notice executes pending withdrawals
/// @param _n The number of withdrawals to complete starting from oldest
function completeWithdrawals(uint32 _n) external nonReentrant {
// TODO: when switched to multi validators model we need to add incentive mechanism to call complete.
uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals);
uint32 startIndex = firstPendingWithdrawalIndex;
numberOfPendingWithdrawals -= toProcess;
firstPendingWithdrawalIndex += toProcess;
for (uint32 i = startIndex; i < startIndex + toProcess; ++i) {
uint16 tokenId = pendingWithdrawals[i].tokenId;
address to = pendingWithdrawals[i].to;
// send fails are ignored hence there is always a direct way to withdraw.
delete pendingWithdrawals[i];
bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId);
uint128 amount = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
// amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20
if (amount != 0) {
balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw -= amount;
bool sent = false;
if (tokenId == 0) {
address payable toPayable = address(uint160(to));
sent = Utils.sendETHNoRevert(toPayable, amount);
} else {
address tokenAddr = governance.tokenAddresses(tokenId);
// we can just check that call not reverts because it wants to withdraw all amount
(sent, ) = address(this).call.gas(
ERC20_WITHDRAWAL_GAS_LIMIT
)(
abi.encodeWithSignature(
"withdrawERC20Guarded(address,address,uint128,uint128)",
tokenAddr,
to,
amount,
amount
)
);
}
if (!sent) {
balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw += amount;
}
}
}
if (toProcess > 0) {
emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess);
}
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n)
external
nonReentrant
{
require(exodusMode, "coe01"); // exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "coe02"); // no deposits to process
for (
uint64 id = firstPriorityRequestId;
id < firstPriorityRequestId + toProcess;
id++
) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
Operations.Deposit memory op = Operations.readDepositPubdata(
priorityRequests[id].pubData
);
bytes22 packedBalanceKey = packAddressAndTokenId(
op.owner,
op.tokenId
);
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op
.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
/// @param _franklinAddr The receiver Layer 2 address
function depositETH(address _franklinAddr) external payable nonReentrant {
requireActive();
registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr);
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender
/// @param _amount Ether amount to withdraw
function withdrawETH(uint128 _amount) external nonReentrant {
registerWithdrawal(0, _amount, msg.sender);
(bool success, ) = msg.sender.call.value(_amount)("");
require(success, "fwe11"); // ETH withdraw failed
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
/// @param _franklinAddr Receiver Layer 2 address
function depositERC20(
IERC20 _token,
uint104 _amount,
address _franklinAddr
) external nonReentrant {
requireActive();
// Get token id by its address
uint16 tokenId = governance.validateTokenAddress(address(_token));
uint256 balance_before = _token.balanceOf(address(this));
require(
Utils.transferFromERC20(
_token,
msg.sender,
address(this),
SafeCast.toUint128(_amount)
),
"fd012"
); // token transfer failed deposit
uint256 balance_after = _token.balanceOf(address(this));
uint128 deposit_amount = SafeCast.toUint128(
balance_after.sub(balance_before)
);
registerDeposit(tokenId, deposit_amount, _franklinAddr);
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender
/// @param _token Token address
/// @param _amount amount to withdraw
function withdrawERC20(IERC20 _token, uint128 _amount)
external
nonReentrant
{
uint16 tokenId = governance.validateTokenAddress(address(_token));
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(
_token,
msg.sender,
_amount,
balance
);
registerWithdrawal(tokenId, withdrawnAmount, msg.sender);
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function fullExit(uint32 _accountId, address _token) external nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "fee11");
uint16 tokenId;
if (_token == address(0)) {
tokenId = 0;
} else {
tokenId = governance.validateTokenAddress(_token);
}
// Priority Queue request
Operations.FullExit memory op = Operations.FullExit({
accountId: _accountId,
owner: msg.sender,
tokenId: tokenId,
amount: 0 // unknown at this point
});
bytes memory pubData = Operations.writeFullExitPubdata(op);
addPriorityRequest(Operations.OpType.FullExit, pubData);
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff;
}
/// @notice Commit block - collect onchain operations, create its commitment, emit BlockCommit event
/// @param _blockNumber Block number
/// @param _feeAccount Account to collect fees
/// @param _newBlockInfo New state of the block. (first element is the account tree root hash, rest of the array is reserved for the future)
/// @param _publicData Operations pubdata
/// @param _ethWitness Data passed to ethereum outside pubdata of the circuit.
/// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation.
function commitBlock(
uint32 _blockNumber,
uint32 _feeAccount,
bytes32[] calldata _newBlockInfo,
bytes calldata _publicData,
bytes calldata _ethWitness,
uint32[] calldata _ethWitnessSizes
) external nonReentrant {
requireActive();
require(_blockNumber == totalBlocksCommitted + 1, "fck11"); // only commit next block
governance.requireActiveValidator(msg.sender);
require(_newBlockInfo.length == 1, "fck13"); // This version of the contract expects only account tree root hash
bytes memory publicData = _publicData;
// Unpack onchain operations and store them.
// Get priority operations number for this block.
uint64 prevTotalCommittedPriorityRequests
= totalCommittedPriorityRequests;
bytes32 withdrawalsDataHash = collectOnchainOps(
_blockNumber,
publicData,
_ethWitness,
_ethWitnessSizes
);
uint64 nPriorityRequestProcessed = totalCommittedPriorityRequests -
prevTotalCommittedPriorityRequests;
createCommittedBlock(
_blockNumber,
_feeAccount,
_newBlockInfo[0],
publicData,
withdrawalsDataHash,
nPriorityRequestProcessed
);
totalBlocksCommitted++;
emit BlockCommit(_blockNumber);
}
/// @notice Block verification.
/// @notice Verify proof -> process onchain withdrawals (accrue balances from withdrawals) -> remove priority requests
/// @param _blockNumber Block number
/// @param _proof Block proof
/// @param _withdrawalsData Block withdrawals data
function verifyBlock(
uint32 _blockNumber,
uint256[] calldata _proof,
bytes calldata _withdrawalsData
) external nonReentrant {
requireActive();
require(_blockNumber == totalBlocksVerified + 1, "fvk11"); // only verify next block
governance.requireActiveValidator(msg.sender);
require(
verifier.verifyBlockProof(
_proof,
blocks[_blockNumber].commitment,
blocks[_blockNumber].chunks
),
"fvk13"
); // proof verification failed
processOnchainWithdrawals(
_withdrawalsData,
blocks[_blockNumber].withdrawalsDataHash
);
deleteRequests(blocks[_blockNumber].priorityOperations);
totalBlocksVerified += 1;
emit BlockVerification(_blockNumber);
}
/// @notice Reverts unverified blocks
/// @param _maxBlocksToRevert the maximum number blocks that will be reverted (use if can't revert all blocks because of gas limit).
function revertBlocks(uint32 _maxBlocksToRevert) external nonReentrant {
require(isBlockCommitmentExpired(), "rbs11"); // trying to revert non-expired blocks.
governance.requireActiveValidator(msg.sender);
uint32 blocksCommited = totalBlocksCommitted;
uint32 blocksToRevert = Utils.minU32(
_maxBlocksToRevert,
blocksCommited - totalBlocksVerified
);
uint64 revertedPriorityRequests = 0;
for (
uint32 i = totalBlocksCommitted - blocksToRevert + 1;
i <= blocksCommited;
i++
) {
Block memory revertedBlock = blocks[i];
require(revertedBlock.committedAtBlock > 0, "frk11"); // block not found
revertedPriorityRequests += revertedBlock.priorityOperations;
delete blocks[i];
}
blocksCommited -= blocksToRevert;
totalBlocksCommitted -= blocksToRevert;
totalCommittedPriorityRequests -= revertedPriorityRequests;
emit BlocksRevert(totalBlocksVerified, blocksCommited);
}
/// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event.
/// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest
/// @dev of existed priority requests expiration block number.
/// @return bool flag that is true if the Exodus mode must be entered.
function triggerExodusIfNeeded() external returns (bool) {
bool trigger = block.number >=
priorityRequests[firstPriorityRequestId].expirationBlock &&
priorityRequests[firstPriorityRequestId].expirationBlock != 0;
if (trigger) {
if (!exodusMode) {
exodusMode = true;
emit ExodusMode();
}
return true;
} else {
return false;
}
}
/// @notice Withdraws token from Franklin to root chain in case of exodus mode. User must provide proof that he owns funds
/// @param _accountId Id of the account in the tree
/// @param _proof Proof
/// @param _tokenId Verified token id
/// @param _amount Amount for owner (must be total amount, not part of it)
function exit(
uint32 _accountId,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external nonReentrant {
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, _tokenId);
require(exodusMode, "fet11"); // must be in exodus mode
require(!exited[_accountId][_tokenId], "fet12"); // already exited
require(
verifier.verifyExitProof(
blocks[totalBlocksVerified].stateRoot,
_accountId,
msg.sender,
_tokenId,
_amount,
_proof
),
"fet13"
); // verification failed
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.add(
_amount
);
exited[_accountId][_tokenId] = true;
}
function setAuthPubkeyHash(bytes calldata _pubkey_hash, uint32 _nonce)
external
nonReentrant
{
require(_pubkey_hash.length == PUBKEY_HASH_BYTES, "ahf10"); // PubKeyHash should be 20 bytes.
require(authFacts[msg.sender][_nonce] == bytes32(0), "ahf11"); // auth fact for nonce should be empty
authFacts[msg.sender][_nonce] = keccak256(_pubkey_hash);
emit FactAuth(msg.sender, _nonce, _pubkey_hash);
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op = Operations.Deposit({
accountId: 0, // unknown at this point
owner: _owner,
tokenId: _tokenId,
amount: _amount
});
bytes memory pubData = Operations.writeDepositPubdata(op);
addPriorityRequest(Operations.OpType.Deposit, pubData);
emit OnchainDeposit(msg.sender, _tokenId, _amount, _owner);
}
/// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event
/// @param _token - token by id
/// @param _amount - token amount
/// @param _to - address to withdraw to
function registerWithdrawal(
uint16 _token,
uint128 _amount,
address payable _to
) internal {
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token);
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(
_amount
);
emit OnchainWithdrawal(_to, _token, _amount);
}
/// @notice Store committed block structure to the storage.
/// @param _nCommittedPriorityRequests - number of priority requests in block
function createCommittedBlock(
uint32 _blockNumber,
uint32 _feeAccount,
bytes32 _newRoot,
bytes memory _publicData,
bytes32 _withdrawalDataHash,
uint64 _nCommittedPriorityRequests
) internal {
require(_publicData.length % CHUNK_BYTES == 0, "cbb10"); // Public data size is not multiple of CHUNK_BYTES
uint32 blockChunks = uint32(_publicData.length / CHUNK_BYTES);
require(verifier.isBlockSizeSupported(blockChunks), "ccb11");
// Create block commitment for verification proof
bytes32 commitment = createBlockCommitment(
_blockNumber,
_feeAccount,
blocks[_blockNumber - 1].stateRoot,
_newRoot,
_publicData
);
blocks[_blockNumber] = Block(
uint32(block.number), // committed at
_nCommittedPriorityRequests, // number of priority onchain ops in block
blockChunks,
_withdrawalDataHash, // hash of onchain withdrawals data (will be used during checking block withdrawal data in verifyBlock function)
commitment, // blocks' commitment
_newRoot // new root
);
}
function emitDepositCommitEvent(
uint32 _blockNumber,
Operations.Deposit memory depositData
) internal {
emit DepositCommit(
_blockNumber,
depositData.accountId,
depositData.owner,
depositData.tokenId,
depositData.amount
);
}
function emitFullExitCommitEvent(
uint32 _blockNumber,
Operations.FullExit memory fullExitData
) internal {
emit FullExitCommit(
_blockNumber,
fullExitData.accountId,
fullExitData.owner,
fullExitData.tokenId,
fullExitData.amount
);
}
/// @notice Gets operations packed in bytes array. Unpacks it and stores onchain operations.
/// @param _blockNumber Franklin block number
/// @param _publicData Operations packed in bytes array
/// @param _ethWitness Eth witness that was posted with commit
/// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation.
/// Priority operations must be committed in the same order as they are in the priority queue.
function collectOnchainOps(
uint32 _blockNumber,
bytes memory _publicData,
bytes memory _ethWitness,
uint32[] memory _ethWitnessSizes
) internal returns (bytes32 withdrawalsDataHash) {
require(_publicData.length % CHUNK_BYTES == 0, "fcs11"); // pubdata length must be a multiple of CHUNK_BYTES
uint64 currentPriorityRequestId = firstPriorityRequestId +
totalCommittedPriorityRequests;
uint256 pubDataPtr = 0;
uint256 pubDataStartPtr = 0;
uint256 pubDataEndPtr = 0;
assembly {
pubDataStartPtr := add(_publicData, 0x20)
}
pubDataPtr = pubDataStartPtr;
pubDataEndPtr = pubDataStartPtr + _publicData.length;
uint64 ethWitnessOffset = 0;
uint16 processedOperationsRequiringEthWitness = 0;
withdrawalsDataHash = EMPTY_STRING_KECCAK;
while (pubDataPtr < pubDataEndPtr) {
Operations.OpType opType;
// read operation type from public data (the first byte per each operation)
assembly {
opType := shr(0xf8, mload(pubDataPtr))
}
// cheap operations processing
if (opType == Operations.OpType.Transfer) {
pubDataPtr += TRANSFER_BYTES;
} else if (opType == Operations.OpType.Noop) {
pubDataPtr += NOOP_BYTES;
} else if (opType == Operations.OpType.TransferToNew) {
pubDataPtr += TRANSFER_TO_NEW_BYTES;
} else {
// other operations processing
// calculation of public data offset
uint256 pubdataOffset = pubDataPtr - pubDataStartPtr;
if (opType == Operations.OpType.Deposit) {
bytes memory pubData = Bytes.slice(
_publicData,
pubdataOffset + 1,
DEPOSIT_BYTES - 1
);
Operations.Deposit memory depositData = Operations
.readDepositPubdata(pubData);
emitDepositCommitEvent(_blockNumber, depositData);
OnchainOperation memory onchainOp = OnchainOperation(
Operations.OpType.Deposit,
pubData
);
commitNextPriorityOperation(
onchainOp,
currentPriorityRequestId
);
currentPriorityRequestId++;
pubDataPtr += DEPOSIT_BYTES;
} else if (opType == Operations.OpType.PartialExit) {
Operations.PartialExit memory data = Operations
.readPartialExitPubdata(_publicData, pubdataOffset + 1);
bool addToPendingWithdrawalsQueue = true;
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
data.owner,
data.tokenId,
data.amount
)
);
pubDataPtr += PARTIAL_EXIT_BYTES;
} else if (opType == Operations.OpType.ForcedExit) {
Operations.ForcedExit memory data = Operations
.readForcedExitPubdata(_publicData, pubdataOffset + 1);
bool addToPendingWithdrawalsQueue = true;
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
data.target,
data.tokenId,
data.amount
)
);
pubDataPtr += FORCED_EXIT_BYTES;
} else if (opType == Operations.OpType.FullExit) {
bytes memory pubData = Bytes.slice(
_publicData,
pubdataOffset + 1,
FULL_EXIT_BYTES - 1
);
Operations.FullExit memory fullExitData = Operations
.readFullExitPubdata(pubData);
emitFullExitCommitEvent(_blockNumber, fullExitData);
bool addToPendingWithdrawalsQueue = false;
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
fullExitData.owner,
fullExitData.tokenId,
fullExitData.amount
)
);
OnchainOperation memory onchainOp = OnchainOperation(
Operations.OpType.FullExit,
pubData
);
commitNextPriorityOperation(
onchainOp,
currentPriorityRequestId
);
currentPriorityRequestId++;
pubDataPtr += FULL_EXIT_BYTES;
} else if (opType == Operations.OpType.ChangePubKey) {
require(
processedOperationsRequiringEthWitness <
_ethWitnessSizes.length,
"fcs13"
); // eth witness data malformed
Operations.ChangePubKey memory op = Operations
.readChangePubKeyPubdata(
_publicData,
pubdataOffset + 1
);
if (
_ethWitnessSizes[processedOperationsRequiringEthWitness] !=
0
) {
bytes memory currentEthWitness = Bytes.slice(
_ethWitness,
ethWitnessOffset,
_ethWitnessSizes[processedOperationsRequiringEthWitness]
);
bool valid = verifyChangePubkeySignature(
currentEthWitness,
op.pubKeyHash,
op.nonce,
op.owner,
op.accountId
);
require(valid, "fpp15"); // failed to verify change pubkey hash signature
} else {
bool valid = authFacts[op.owner][op.nonce] ==
keccak256(abi.encodePacked(op.pubKeyHash));
require(valid, "fpp16"); // new pub key hash is not authenticated properly
}
ethWitnessOffset += _ethWitnessSizes[processedOperationsRequiringEthWitness];
processedOperationsRequiringEthWitness++;
pubDataPtr += CHANGE_PUBKEY_BYTES;
} else {
revert("fpp14"); // unsupported op
}
}
}
require(pubDataPtr == pubDataEndPtr, "fcs12"); // last chunk exceeds pubdata
require(ethWitnessOffset == _ethWitness.length, "fcs14"); // _ethWitness was not used completely
require(
processedOperationsRequiringEthWitness == _ethWitnessSizes.length,
"fcs15"
); // _ethWitnessSizes was not used completely
require(
currentPriorityRequestId <=
firstPriorityRequestId + totalOpenPriorityRequests,
"fcs16"
); // fcs16 - excess priority requests in pubdata
totalCommittedPriorityRequests =
currentPriorityRequestId -
firstPriorityRequestId;
}
/// @notice Checks that signature is valid for pubkey change message
/// @param _signature Signature
/// @param _newPkHash New pubkey hash
/// @param _nonce Nonce used for message
/// @param _ethAddress Account's ethereum address
/// @param _accountId Id of zkSync account
function verifyChangePubkeySignature(
bytes memory _signature,
bytes20 _newPkHash,
uint32 _nonce,
address _ethAddress,
uint32 _accountId
) internal pure returns (bool) {
bytes memory signedMessage = abi.encodePacked(
"\x19Ethereum Signed Message:\n152",
"Register zkSync pubkey:\n\n",
Bytes.bytesToHexASCIIBytes(abi.encodePacked(_newPkHash)),
"\n",
"nonce: 0x",
Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_nonce)),
"\n",
"account id: 0x",
Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_accountId)),
"\n\n",
"Only sign this message for a trusted client!"
);
address recoveredAddress = Utils.recoverAddressFromEthSignature(
_signature,
signedMessage
);
return recoveredAddress == _ethAddress;
}
/// @notice Creates block commitment from its data
/// @param _blockNumber Block number
/// @param _feeAccount Account to collect fees
/// @param _oldRoot Old tree root
/// @param _newRoot New tree root
/// @param _publicData Operations pubdata
/// @return block commitment
function createBlockCommitment(
uint32 _blockNumber,
uint32 _feeAccount,
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _publicData
) internal view returns (bytes32 commitment) {
bytes32 hash = sha256(
abi.encodePacked(uint256(_blockNumber), uint256(_feeAccount))
);
hash = sha256(abi.encodePacked(hash, uint256(_oldRoot)));
hash = sha256(abi.encodePacked(hash, uint256(_newRoot)));
/// The code below is equivalent to `commitment = sha256(abi.encodePacked(hash, _publicData))`
/// We use inline assembly instead of this concise and readable code in order to avoid copying of `_publicData` (which saves ~90 gas per transfer operation).
/// Specifically, we perform the following trick:
/// First, replace the first 32 bytes of `_publicData` (where normally its length is stored) with the value of `hash`.
/// Then, we call `sha256` precompile passing the `_publicData` pointer and the length of the concatenated byte buffer.
/// Finally, we put the `_publicData.length` back to its original location (to the first word of `_publicData`).
assembly {
let hashResult := mload(0x40)
let pubDataLen := mload(_publicData)
mstore(_publicData, hash)
// staticcall to the sha256 precompile at address 0x2
let success := staticcall(
gas,
0x2,
_publicData,
add(pubDataLen, 0x20),
hashResult,
0x20
)
mstore(_publicData, pubDataLen)
// Use "invalid" to make gas estimation work
switch success
case 0 {
invalid()
}
commitment := mload(hashResult)
}
}
/// @notice Checks that operation is same as operation in priority queue
/// @param _onchainOp The operation
/// @param _priorityRequestId Operation's id in priority queue
function commitNextPriorityOperation(
OnchainOperation memory _onchainOp,
uint64 _priorityRequestId
) internal view {
Operations.OpType priorReqType = priorityRequests[_priorityRequestId]
.opType;
bytes memory priorReqPubdata = priorityRequests[_priorityRequestId]
.pubData;
require(priorReqType == _onchainOp.opType, "nvp12"); // incorrect priority op type
if (_onchainOp.opType == Operations.OpType.Deposit) {
require(
Operations.depositPubdataMatch(
priorReqPubdata,
_onchainOp.pubData
),
"vnp13"
);
} else if (_onchainOp.opType == Operations.OpType.FullExit) {
require(
Operations.fullExitPubdataMatch(
priorReqPubdata,
_onchainOp.pubData
),
"vnp14"
);
} else {
revert("vnp15"); // invalid or non-priority operation
}
}
/// @notice Processes onchain withdrawals. Full exit withdrawals will not be added to pending withdrawals queue
/// @dev NOTICE: must process only withdrawals which hash matches with expectedWithdrawalsDataHash.
/// @param withdrawalsData Withdrawals data
/// @param expectedWithdrawalsDataHash Expected withdrawals data hash
function processOnchainWithdrawals(
bytes memory withdrawalsData,
bytes32 expectedWithdrawalsDataHash
) internal {
require(
withdrawalsData.length % ONCHAIN_WITHDRAWAL_BYTES == 0,
"pow11"
); // pow11 - withdrawalData length is not multiple of ONCHAIN_WITHDRAWAL_BYTES
bytes32 withdrawalsDataHash = EMPTY_STRING_KECCAK;
uint256 offset = 0;
uint32 localNumberOfPendingWithdrawals = numberOfPendingWithdrawals;
while (offset < withdrawalsData.length) {
(
bool addToPendingWithdrawalsQueue,
address _to,
uint16 _tokenId,
uint128 _amount
) = Operations.readWithdrawalData(withdrawalsData, offset);
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
// after this all writes to this slot will cost 5k gas
balancesToWithdraw[packedBalanceKey] = BalanceToWithdraw({
balanceToWithdraw: balance.add(_amount),
gasReserveValue: 0xff
});
if (addToPendingWithdrawalsQueue) {
pendingWithdrawals[firstPendingWithdrawalIndex +
localNumberOfPendingWithdrawals] = PendingWithdrawal(
_to,
_tokenId
);
localNumberOfPendingWithdrawals++;
}
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
_to,
_tokenId,
_amount
)
);
offset += ONCHAIN_WITHDRAWAL_BYTES;
}
require(withdrawalsDataHash == expectedWithdrawalsDataHash, "pow12"); // pow12 - withdrawals data hash not matches with expected value
if (numberOfPendingWithdrawals != localNumberOfPendingWithdrawals) {
emit PendingWithdrawalsAdd(
firstPendingWithdrawalIndex + numberOfPendingWithdrawals,
firstPendingWithdrawalIndex + localNumberOfPendingWithdrawals
);
}
numberOfPendingWithdrawals = localNumberOfPendingWithdrawals;
}
/// @notice Checks whether oldest unverified block has expired
/// @return bool flag that indicates whether oldest unverified block has expired
function isBlockCommitmentExpired() internal view returns (bool) {
return (totalBlocksCommitted > totalBlocksVerified &&
blocks[totalBlocksVerified + 1].committedAtBlock > 0 &&
block.number >
blocks[totalBlocksVerified + 1].committedAtBlock +
EXPECT_VERIFICATION_IN);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "fre11"); // exodus mode activated
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(
Operations.OpType _opType,
bytes memory _pubData
) internal {
// Expiration block is: current block number + priority expiration delta
uint256 expirationBlock = block.number + PRIORITY_EXPIRATION;
uint64 nextPriorityRequestId = firstPriorityRequestId +
totalOpenPriorityRequests;
priorityRequests[nextPriorityRequestId] = PriorityOperation({
opType: _opType,
pubData: _pubData,
expirationBlock: expirationBlock
});
emit NewPriorityRequest(
msg.sender,
nextPriorityRequestId,
_opType,
_pubData,
expirationBlock
);
totalOpenPriorityRequests++;
}
/// @notice Deletes processed priority requests
/// @param _number The number of requests
function deleteRequests(uint64 _number) internal {
require(_number <= totalOpenPriorityRequests, "pcs21"); // number is higher than total priority requests number
uint64 numberOfRequestsToClear = Utils.minU64(
_number,
MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY
);
uint64 startIndex = firstPriorityRequestId;
for (
uint64 i = startIndex;
i < startIndex + numberOfRequestsToClear;
i++
) {
delete priorityRequests[i];
}
totalOpenPriorityRequests -= _number;
firstPriorityRequestId += _number;
totalCommittedPriorityRequests -= _number;
}
}
| Checks whether oldest unverified block has expired return bool flag that indicates whether oldest unverified block has expired | function isBlockCommitmentExpired() internal view returns (bool) {
return (totalBlocksCommitted > totalBlocksVerified &&
blocks[totalBlocksVerified + 1].committedAtBlock > 0 &&
block.number >
blocks[totalBlocksVerified + 1].committedAtBlock +
EXPECT_VERIFICATION_IN);
}
| 5,479,397 |
./partial_match/1/0x6c754f774402Ec4bD3556EEA769e87F22489621E/sources/ClipGrave.sol | 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));
}
| 2,824,083 |
pragma solidity >=0.4.0 <0.6.0;
//^0.4.18;
// showing the exchange of product between drugcontroller and certifier
//Actually it is DrugDetails now
/*interface Regulator{
function sendescrow(address escrowparticipator, bytes32 escrowparticipatorname, uint escrowparticipatoramount) external;
function returnbackescrow (address _escrowvictimaddress, bytes32 _escrowvictimmame, uint _escrowvictimmoney) external;
//LASTOWNER WILL BE PAID HERE
//LASTOWNER WILL BE PAID HERE
function deposit(address donator, address receipient, uint amount) external;
}
*/
contract EscrowComplianceCecker {
uint public amountrequired =2 ;
address payable public escrowownaddress=0xfd2C3e27BfACcf842424e48dC72cb18ba48E9457;
uint escrowbalance =0;
uint value;
uint m;
mapping(uint256 => bool) usedNonces;
struct EscrowSentBack{
address payable escrowvictimaddress;
bytes32 escrowvictimmame;
uint escrowvictimmoney;
bytes32 escrowvictimtimestamp;
uint escrowvictimcount;
mapping (address => EscrowSentBack[]) escrowteeser;
}
EscrowSentBack[] public punishings;
struct EscrowObtained{
address payable escrowparticipantaddress;
bytes32 escrowparticipantname;
uint escrowparticipantsinitialamountputin;
bytes32 escrowparticipanttimestamp;
uint escrowparticipantcount;
mapping (address => EscrowObtained[]) escrowobtainees;
}
EscrowObtained[] public proposals;
EscrowObtained escrowobtainee;
EscrowSentBack escrowtees;
/* constructor(uint _amountrequired) public {
amountrequired = _amountrequired;
}
*/
function sendescrow(address payable escrowparticipator, bytes32 escrowparticipatorname, uint escrowparticipatoramount) public {
escrowobtainee.escrowobtainees;
escrowobtainee.escrowparticipantcount;
m =escrowobtainee.escrowparticipantcount;
uint obtcounter = m++;
escrowobtainee.escrowparticipantaddress= escrowparticipator;
escrowobtainee.escrowparticipantname=escrowparticipatorname;
require(amountrequired <= escrowparticipatoramount, "This is not enough for escrow");
escrowobtainee.escrowparticipantsinitialamountputin =escrowparticipatoramount;
uint escrowedvaluesent = escrowobtainee.escrowparticipantsinitialamountputin;
// knownEntity[entityAddress];
//(entityStructs[rowNumber].entityAddress != entityAddress;
escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantsinitialamountputin =escrowedvaluesent;
escrowbalance += escrowobtainee.escrowparticipantsinitialamountputin;
proposals.push(EscrowComplianceCecker.EscrowObtained({
escrowparticipantaddress: escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantaddress,
escrowparticipantname:escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantname,
escrowparticipantsinitialamountputin:escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantsinitialamountputin,
escrowparticipanttimestamp:escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipanttimestamp,
escrowparticipantcount:escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantcount
// I HAVE TO ADD THE OTHER DETAILS
}));
}
//we have to receive latest escrow
function returnbackescrow (address payable _escrowvictimaddress, bytes32 _escrowvictimmame, uint _escrowvictimmoney) public {
escrowtees.escrowteeser;
escrowobtainee.escrowobtainees;
escrowobtainee.escrowparticipantaddress;
// uint obtcounter;
uint obtanothercounter;
require(escrowobtainee.escrowobtainees[ escrowobtainee.escrowparticipantaddress][obtanothercounter].escrowparticipantaddress == _escrowvictimaddress);
m =escrowtees.escrowvictimcount;
uint counter = m++;
escrowtees.escrowvictimaddress= _escrowvictimaddress;
escrowtees.escrowvictimmame=_escrowvictimmame;
escrowtees.escrowvictimmoney =_escrowvictimmoney;
escrowtees.escrowteeser[_escrowvictimaddress][counter].escrowvictimmoney = escrowobtainee.escrowobtainees[ escrowobtainee.escrowparticipantaddress][obtanothercounter].escrowparticipantsinitialamountputin;
escrowtees.escrowteeser[_escrowvictimaddress][counter].escrowvictimaddress =escrowobtainee.escrowobtainees[ escrowobtainee.escrowparticipantaddress][obtanothercounter].escrowparticipantaddress;
// escrowtees.escrowteeser[_escrowvictimaddress][counter].escrowvictimtimestamp =now;
uint mymoney = escrowtees.escrowteeser[_escrowvictimaddress][counter].escrowvictimmoney;
address payable receipientaddress = escrowtees.escrowteeser[_escrowvictimaddress][counter].escrowvictimaddress;
require(msg.sender == escrowownaddress);
escrowownaddress.transfer(mymoney);
withdraw(mymoney,escrowbalance);
emit Sent(escrowownaddress, receipientaddress, mymoney);
punishings.push(EscrowComplianceCecker.EscrowSentBack({
escrowvictimaddress: escrowtees.escrowteeser[_escrowvictimaddress][counter].escrowvictimaddress,
escrowvictimmame: escrowtees.escrowteeser[_escrowvictimaddress][counter].escrowvictimmame,
escrowvictimmoney: escrowtees.escrowteeser[_escrowvictimaddress][counter].escrowvictimmoney,
escrowvictimtimestamp: escrowtees.escrowteeser[_escrowvictimaddress][counter]. escrowvictimtimestamp,
escrowvictimcount: escrowtees.escrowteeser[_escrowvictimaddress][counter].escrowvictimcount
// I HAVE TO ADD THE OTHER DETAILS
}));
}
function deposit(address payable donator, address payable receipient, uint amount) public payable{
donator.transfer(amount);
escrowbalance +=amount;
escrowownaddress =receipient;
}
function withdraw(uint balanceamount, uint escrowbalancenow) public payable {
escrowbalance = escrowbalancenow;
require(balanceamount <= escrowbalance, "Insufficient balance.");
escrowbalance -=balanceamount;
}
function balances() public view returns(uint) {
return escrowbalance;
}
event Sent(address payable from, address payable receipientaddress, uint amount);
// THE NEW RECEIVER WILL USE THIS TO SIGN THE MESSAGE
//for the escrowobtainedaddress = receipient address produce this amount
//for deleting index
//(entityList[entityStructs[entityAddress].listPointer] == entityAddress);
//WE WILL USE IT TO RETRIEVE INFORMATION FOR THE ESCROW SO THAT THE ESCROW CAN ALSO SEE
//WHAT IS HAPPENING.
// THIS FUNCTION IS CALLED BY INDUSTRY; HE CLAIMS GOOD AFTER EXCHANGE;
function claimPayment( uint256 amount, uint256 nonce, bytes memory signature,address payable receipientaddress)
public {
require(!usedNonces[nonce]);
usedNonces[nonce] = true;
// this recreates the message that was signed on the client
bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount,
nonce, this)));
require(recoverSigner(message, signature) == escrowownaddress);
msg.sender.transfer(amount);
withdraw(amount,escrowbalance);
emit Sent(msg.sender, receipientaddress, amount);
}
/// destroy the contract and reclaim the leftover funds.
function kill() public {
require(msg.sender == escrowownaddress);
selfdestruct(msg.sender);
}
/// signature methods.
function splitSignature(bytes memory sig)
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(sig.length == 65);
assembly {
// first 32 bytes, after the length prefix.
r := mload(add(sig, 32))
// second 32 bytes.
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes).
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
// HERE IS WHERE RECOVER SIGNER IS PASSED TO HIM SO THAT HE CAN GET HIS MONEY
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
(uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
/// builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
contract Industry is EscrowComplianceCecker {
// `TokenCreator` is a contract type that is defined below.
// It is fine to reference it as long as it is not used
// to create a new contract.
uint i;
uint strucount;
//This is the Processing Entitiy , whether farmer, manufacturer or sales
struct ProcessingEntity{
address payable currentowner;
address payable receiver;
uint256 publickey;
bytes32 currentownername;
bytes32 receivername;
uint256 currentownerprocessingfee;
bytes32 role;
uint balance;
bytes32 RFIDofdrugtobesent;
uint currentownerscount;
mapping (bytes32 => ProcessingEntity[]) processingentities;
}
struct ProcessingEntityStructure{
bytes32 location;
bool hasdrug;
uint escrowamount;
address payable lastdestination;
address payable justhandedoveraddres;
bytes32 RFIDofthisdrug;
address payable manufacturerofdrugstobesent;
uint currentpersoncount;
mapping (bytes32 => ProcessingEntityStructure[]) ProcessingEntityStructures;
}
//This is the drug
struct Drug{
address payable manufacturer;
address payable currentdrugpossessor;
bytes32 RFID;
bytes32 drugname;
uint cost;
int temperature;
int concentration;
bytes32 location;
bytes32 drugquality;
mapping (bytes32 => Drug[]) drugs;
uint numOfDrugCount;
}
// This is the nuber of phases that has taken place
//We are tokenizing the process
struct Processes{
address currentproces;
bytes32 timestamp;
bytes32 drugname;
uint numberofProcessingEntities;
bytes32 location;
address payable receipient;
uint escrowvalue;
mapping (address => ProcessingEntity) Processingentities;
uint numOfProcesses;
mapping (uint => Processes) processbatch;
mapping (bytes32 => Drug[]) drugRFID;
}
ProcessingEntityStructure processingstructures;
ProcessingEntityStructure[] public processingstructureses;
Processes procedure;
Processes[] public procedures;
ProcessingEntity procent;
ProcessingEntity[] public procenter;
Drug[] public self;
Drug me;
//This is the Industry's constructor
/* constructor(bytes32 _name, address currentowners, uint c ) public {
i = c;
procent.currentownername = _name;
procent.currentowner = currentowners;
procent.currentowner = msg.sender;
}
*/
//Now we will engage the processing phase here
function newProcessingPhase (address payable _sender, bytes32 _sendername,address payable _receipient, bytes32 receipientname,bytes32 _RFID, address payable _lastdestination, uint processesnumber) internal {
uint v;
bool hasenrolleded = false;
procent.RFIDofdrugtobesent= _RFID;
processingstructures.RFIDofthisdrug =_RFID;
procent.currentownerscount;
procent.currentowner = _sender;
procent.currentownername = _sendername;
procent.receiver = _receipient;
procent.receivername = receipientname;
processingstructures.lastdestination = _lastdestination;
me.RFID = _RFID;
uint numOfProcesses = processesnumber;
uint numOfDrugCount;
uint currentownerscount;
uint currentpersoncount;
numOfProcesses= procedure.numOfProcesses++;
numOfDrugCount = me.numOfDrugCount;
currentownerscount = currentownerscount++;
currentpersoncount = currentownerscount++;
procent.currentownerscount = currentownerscount;
processingstructures.currentpersoncount =currentpersoncount;
me.drugs;
// self[me.RFID][numOfDrugCount] = Drug[self.RFID][numOfDrugCount];
sendescrows(procenter[currentownerscount].currentowner, procenter[currentownerscount].currentownername, processingstructureses[currentpersoncount].escrowamount, v);
// SETTING UP!...Broke up the details because of deep stack depth
//Setting Up Enemy Details
ObtainProcessingEntity(procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentowner,procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].receiver, procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].publickey,procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownername,
procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].receivername,procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownerprocessingfee);
// processingstructureses
// Setting Up Next Escrow and Processamount
ObtainProcessingEntityDetails( procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].role,procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].balance,processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].location,processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].hasdrug,
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].escrowamount,processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].lastdestination,processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].justhandedoveraddres);
// Setting Up More of People's Details
ObtainProcessingEntityStatus(procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].RFIDofdrugtobesent,processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].manufacturerofdrugstobesent,procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownerscount);
//SETTING UP MORE OF DRUGDETAILS.......
ObtainDrugInfo(me.drugs[me.RFID][numOfDrugCount].currentdrugpossessor,
me.drugs[me.RFID][numOfDrugCount].RFID, me.drugs[me.RFID][numOfDrugCount].cost,me.drugs[me.RFID][numOfDrugCount].drugname);
// Setting up the drug attributes
ObtainDrugInfoAdditional( me.drugs[me.RFID][numOfDrugCount].temperature,me.drugs[me.RFID][numOfDrugCount].concentration,me.drugs[me.RFID][numOfDrugCount].location, me.drugs[me.RFID][numOfDrugCount].numOfDrugCount, me.drugs[me.RFID][numOfDrugCount].manufacturer, me.drugs[me.RFID][numOfDrugCount].drugquality);
self.push(Industry.Drug({
currentdrugpossessor: me.drugs[me.RFID][numOfDrugCount].currentdrugpossessor,
RFID:me.drugs[me.RFID][numOfDrugCount].RFID,
cost:me.drugs[me.RFID][numOfDrugCount].cost,
drugname:me.drugs[me.RFID][numOfDrugCount].drugname,
temperature:me.drugs[me.RFID][numOfDrugCount].temperature,
concentration:me.drugs[me.RFID][numOfDrugCount].concentration,
location:me.drugs[me.RFID][numOfDrugCount].location,
numOfDrugCount:me.drugs[me.RFID][numOfDrugCount].numOfDrugCount,
manufacturer: me.drugs[me.RFID][numOfDrugCount].manufacturer,
drugquality:me.drugs[me.RFID][numOfDrugCount].drugquality
// i have to ensure other details are kept
}));
procenter.push(ProcessingEntity(
{
currentowner: procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentowner,
receiver:procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].receiver,
publickey: procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].publickey,
currentownername: procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownername,
receivername: procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].receivername,
currentownerprocessingfee:procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownerprocessingfee,
role: procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].role,
balance: procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].balance,
RFIDofdrugtobesent:procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].RFIDofdrugtobesent,
currentownerscount:procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownerscount
// I HAVE TO ADD THE OTHER DETAILS
}));
processingstructureses.push(ProcessingEntityStructure(
{
location:processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].location,
hasdrug: processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].hasdrug,
escrowamount: processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].escrowamount,
lastdestination: processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].lastdestination,
justhandedoveraddres:processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].justhandedoveraddres,
RFIDofthisdrug:processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].RFIDofthisdrug,
manufacturerofdrugstobesent:processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].manufacturerofdrugstobesent,
currentpersoncount:processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].currentpersoncount
// I HAVE TO ADD THE OTHER DETAILS
}));
procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownerscount = procent.currentownerscount ;
changecurrentownership( procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].receivername, procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownername,
procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentowner,procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].receiver ,processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].justhandedoveraddres,processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].manufacturerofdrugstobesent,
procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].RFIDofdrugtobesent,procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownerscount, processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].hasdrug,me.drugs[me.RFID][numOfDrugCount].numOfDrugCount, procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownerprocessingfee);
procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownerscount = numOfProcesses;
hasbeenenrolled(procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].receiver,hasenrolleded);
checklastdestination(procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].receiver, processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].lastdestination,procent.processingentities[procent.RFIDofdrugtobesent][currentownerscount].currentownerscount,me.RFID);
endphases( numOfDrugCount,processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][currentpersoncount].lastdestination);
me.drugs[me.RFID][numOfDrugCount].numOfDrugCount =numOfDrugCount;
}
//function showDetails() public pure {
//we have to console.log() it;
// console.log();
//}
function providecustomerpermission( bytes32 _RFID) public {
bool givepermito;
procent.currentownerscount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].role;
givepermito = false;
givepermitte(givepermito);
require ( givepermitte(givepermito) == true);return;
require(procent.processingentities[procent.RFIDofdrugtobesent][i].role== 'manufacturer', "Permission not given by manufacturer");return;
PrintthemAll(_RFID);
}
function givepermitte ( bool givepermits) public pure returns (bool) {
givepermits = true;
return givepermits;
}
function makeDeposit(address payable donationmaker, uint amount) public payable {
address payable cashtoescrow=0xfd2C3e27BfACcf842424e48dC72cb18ba48E9457;
procent.currentownerscount;
i=procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner=donationmaker;
require(amount <= procent.processingentities[procent.RFIDofdrugtobesent][i].balance, "Insufficient balance.");
EscrowComplianceCecker.deposit( procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner, cashtoescrow, amount);
donationmaker.transfer(amount);
emit Sent(donationmaker, cashtoescrow, amount);
procent.processingentities[procent.RFIDofdrugtobesent][i].balance-=amount;
}
function PrintthemAll( bytes32 myRFID) public{
PrintProcessingEntity(myRFID);
PrintProcessingEntityDetails(myRFID);
PrintProcessingEntityStatus(myRFID);
PrintDrugInfo(myRFID);
PrintDrugInfoAdditional(myRFID);
}
function DetectGoodsQuality(bytes32 _RFID) public {
procent.currentownerscount;
me.numOfDrugCount;
uint w = me.numOfDrugCount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
require(me.drugs[me.RFID][w].RFID ==_RFID);return;
if( me.drugs[me.RFID][w].temperature <= (me.drugs[me.RFID][w].temperature)/3 && me.drugs[me.RFID][w].concentration <= (self[w].concentration )/3){
me.drugs[me.RFID][w].drugquality = "Moderately Low";
}
else if ( me.drugs[me.RFID][w].temperature <= (me.drugs[me.RFID][w].temperature)/4 && me.drugs[me.RFID][w].concentration <= (self[w].concentration )/4){
me.drugs[me.RFID][w].drugquality = "Below Standard";
}
else {
me.drugs[me.RFID][w].drugquality= " Standard";
}
}
// This is where we get the whole the person from the industry's details
// I am editing from here
function hasbeenenrolled (address payable enroller,bool hasenrolled) public
{
hasenrolled = false;
procent.currentownerscount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner= enroller;
hasenrolled = true;
}
function ObtainProcessingEntity(address payable fellowowner, address payable fellowreceiver, uint256 fellowpublickey,bytes32 fellowcurrentownername,
bytes32 fellowreceivername,uint256 fellowcurrentprocessingfee) public {
me.RFID;
procent.RFIDofdrugtobesent;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner=fellowowner;
procent.processingentities[procent.RFIDofdrugtobesent][i].receiver=fellowreceiver;
procent.processingentities[procent.RFIDofdrugtobesent][i].publickey=fellowpublickey;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownername =fellowcurrentownername;
procent.processingentities[procent.RFIDofdrugtobesent][i].receivername =fellowreceivername;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownerprocessingfee=fellowcurrentprocessingfee;
}
function ObtainProcessingEntityDetails(bytes32 mybigrole,uint mygreatbalance,bytes32 mynicelocation, bool ihavethisdrug, uint ihaveescrowamount, address payable ourlastdestination,address payable lookmyjustendedaddress) public {
me.RFID;
procent.RFIDofdrugtobesent;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].role=mybigrole;
procent.processingentities[procent.RFIDofdrugtobesent][i].balance=mygreatbalance;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].location=mynicelocation;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].hasdrug=ihavethisdrug;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].escrowamount=ihaveescrowamount;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].lastdestination=ourlastdestination;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].justhandedoveraddres=lookmyjustendedaddress;
}
function ObtainProcessingEntityStatus(bytes32 theRFIDofthisdrug,address payable manufacturerofdrugimustsend,uint iamcountingcurrentowners) public {
me.RFID ;
procent.RFIDofdrugtobesent;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].RFIDofdrugtobesent=theRFIDofthisdrug;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].manufacturerofdrugstobesent=manufacturerofdrugimustsend;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownerscount=iamcountingcurrentowners;
}
function ObtainDrugInfo(address payable iamthecurrentdrugprocessor,
bytes32 thisisgoingtobeRFID, uint thisismygreatestcost,bytes32 tellmethedrugme) public {
me.RFID ;
procent.RFIDofdrugtobesent;
uint w = me.numOfDrugCount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
me.drugs[me.RFID][w].currentdrugpossessor=iamthecurrentdrugprocessor;
me.drugs[me.RFID][w].RFID=thisisgoingtobeRFID;
me.drugs[me.RFID][w].cost=thisismygreatestcost;
me.drugs[me.RFID][w].drugname=tellmethedrugme;
}
function ObtainDrugInfoAdditional( int thetemperature, int theconcentration,bytes32 thegreatlocation, uint thenumberofcountihave, address payable themanufacturersihave, bytes32 thedrugqualityihave) public{
me.RFID;
procent.RFIDofdrugtobesent;
uint w = me.numOfDrugCount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
me.drugs[me.RFID][w].temperature=thetemperature;
me.drugs[me.RFID][w].concentration=theconcentration;
me.drugs[me.RFID][w].location=thegreatlocation;
me.drugs[me.RFID][w].numOfDrugCount=thenumberofcountihave;
me.drugs[me.RFID][w].manufacturer=themanufacturersihave;
me.drugs[me.RFID][w].drugquality=thedrugqualityihave;
}
// I have processing entities here
function PrintProcessingEntity(bytes32 _RFID) public returns(address payable a, address payable b, uint256 c,bytes32 d,
bytes32 e,uint256 f){
me.RFID =_RFID;
procent.RFIDofdrugtobesent=_RFID;
uint w = me.numOfDrugCount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner=a;
procent.processingentities[procent.RFIDofdrugtobesent][i].receiver=b;
procent.processingentities[procent.RFIDofdrugtobesent][i].publickey=c;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownername =d;
procent.processingentities[procent.RFIDofdrugtobesent][i].receivername =e;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownerprocessingfee=f;
assert(procent.processingentities[procent.RFIDofdrugtobesent][i].RFIDofdrugtobesent==procent.RFIDofdrugtobesent);
assert(me.drugs[me.RFID][w].RFID==me.RFID);
// procent.processingentities[procent.RFIDofdrugtobesent][i];
return (a,b,c,d,e,f );
}
function PrintProcessingEntityDetails(bytes32 _RFID) public returns(bytes32 g,uint h,bytes32 ii, bool j, uint k, address payable l,address payable m){
me.RFID =_RFID;
procent.RFIDofdrugtobesent=_RFID;
uint w = me.numOfDrugCount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].role=g;
procent.processingentities[procent.RFIDofdrugtobesent][i].balance=h;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].location=ii;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].hasdrug=j;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].escrowamount=k;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].lastdestination=l;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].justhandedoveraddres=m;
require(procent.processingentities[procent.RFIDofdrugtobesent][i].RFIDofdrugtobesent==procent.RFIDofdrugtobesent);
require(me.drugs[me.RFID][w].RFID==me.RFID);
// procent.processingentities[procent.RFIDofdrugtobesent][i];
return (g,h,ii,j,k,l,m );
}
function PrintProcessingEntityStatus(bytes32 _RFID) public returns(bytes32 n,address payable o,uint p){
me.RFID =_RFID;
procent.RFIDofdrugtobesent=_RFID;
uint w = me.numOfDrugCount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].RFIDofdrugtobesent=n;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].manufacturerofdrugstobesent=o;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownerscount=p;
require(procent.processingentities[procent.RFIDofdrugtobesent][i].RFIDofdrugtobesent==procent.RFIDofdrugtobesent);
require(me.drugs[me.RFID][w].RFID==me.RFID);
// procent.processingentities[procent.RFIDofdrugtobesent][i];
return (n,o,p );
}
function PrintDrugInfo(bytes32 _RFID) public returns(address payable q,
bytes32 r, uint s,bytes32 t){
me.RFID =_RFID;
procent.RFIDofdrugtobesent=_RFID;
uint w = me.numOfDrugCount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
me.drugs[me.RFID][w].currentdrugpossessor=q;
me.drugs[me.RFID][w].RFID=r;
me.drugs[me.RFID][w].cost=s;
me.drugs[me.RFID][w].drugname=t;
require(procent.processingentities[procent.RFIDofdrugtobesent][i].RFIDofdrugtobesent==procent.RFIDofdrugtobesent);
require(me.drugs[me.RFID][w].RFID==me.RFID);
// procent.processingentities[procent.RFIDofdrugtobesent][i];
return (q,r,s,t );
}
function PrintDrugInfoAdditional(bytes32 _RFID) public returns( int u, int v,bytes32 ww, uint x, address payable y, bytes32 z){
me.RFID =_RFID;
procent.RFIDofdrugtobesent=_RFID;
uint w = me.numOfDrugCount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
me.drugs[me.RFID][w].temperature=u;
me.drugs[me.RFID][w].concentration=v;
me.drugs[me.RFID][w].location=ww;
me.drugs[me.RFID][w].numOfDrugCount=x;
me.drugs[me.RFID][w].manufacturer=y;
me.drugs[me.RFID][w].drugquality=z;
require(procent.processingentities[procent.RFIDofdrugtobesent][i].RFIDofdrugtobesent==procent.RFIDofdrugtobesent);
require(me.drugs[me.RFID][w].RFID==me.RFID);
// procent.processingentities[procent.RFIDofdrugtobesent][i];
return (u,v,ww,x,y,z );
}
//The industry person has to oblidge to an escrow by making a small deposit
function createEscrow(uint escrowvalue, uint balancers) public {
procent.currentownerscount;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].balance=balancers;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].escrowamount = escrowvalue;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].escrowamount= procent.processingentities[procent.RFIDofdrugtobesent][i].balance/4;
procent.processingentities[procent.RFIDofdrugtobesent][i].balance-= processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].escrowamount;
}
function sendescrows(address payable escrowparticipator, bytes32 escrowparticipatorname, uint escrowparticipatoramount, uint v) public {
procent.currentownerscount =v;
processingstructures.currentpersoncount =v;
i =procent.currentownerscount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner= escrowparticipator;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownername=escrowparticipatorname;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].escrowamount =escrowparticipatoramount;
createEscrow( processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].escrowamount,procent.processingentities[procent.RFIDofdrugtobesent][i].balance);
EscrowComplianceCecker.sendescrow( procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner,procent.processingentities[procent.RFIDofdrugtobesent][i].currentownername,processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].escrowamount);
}
function sendescrow(address payable escrowparticipator, bytes32 escrowparticipatorname, uint escrowparticipatoramount) public {
EscrowComplianceCecker.sendescrow( escrowparticipator, escrowparticipatorname, escrowparticipatoramount);
}
function returnbackescrow (address payable _escrowvictimaddress, bytes32 _escrowvictimmame, uint _escrowvictimmoney) public{
EscrowComplianceCecker.returnbackescrow( _escrowvictimaddress, _escrowvictimmame, _escrowvictimmoney) ;
}
function deposit(address payable donator, address payable receipient, uint amount) public payable {
EscrowComplianceCecker.deposit( donator, receipient, amount);
}
// This is where we check the last destination to see if the drug has arrived mostly at point of purchase
//In some cases different shops may buy assigning the last destination may be a bit tricky on that note
function checklastdestination(address payable _receiver,address payable _lastdestination,uint256 s, bytes32 _RFID) public {
procent.currentownerscount=s;
bool _lastdestinationreached = false;
i =procent.currentownerscount;
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
procent.processingentities[procent.RFIDofdrugtobesent][i].receiver=_receiver;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].lastdestination =_lastdestination;
if(procent.processingentities[procent.RFIDofdrugtobesent][i].receiver ==processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].lastdestination){
_lastdestinationreached = true;
PrintProcessingEntity(_RFID);
}
}
// We ensure that they verify so that we can show their details else escrow is launched;
/* function checksignature() public {
}
*/
//For each phase end it makes an incrament for another drug possibly
function endphases(uint numOfDrugCounts, address payable _lastdestination) public returns(uint){
//I have to add i
processingstructures.currentpersoncount;
strucount =processingstructures.currentpersoncount;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].lastdestination =_lastdestination;
if(msg.sender == processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].lastdestination){
uint numOfDrugCount;
numOfDrugCount= numOfDrugCounts;
me.numOfDrugCount = numOfDrugCount++;
return me.numOfDrugCount;
}
}
function withdraw(uint balanceamount, uint escrowbalancenow) public payable {
EscrowComplianceCecker.withdraw(balanceamount,escrowbalancenow);
}
function balances() public view returns(uint){
EscrowComplianceCecker.balances();
}
function claimPayment( uint256 amount, uint256 nonce, bytes memory signature,address payable receipientaddress)
public {
EscrowComplianceCecker.claimPayment(amount, nonce, signature, receipientaddress);
}
// Here is the place where we change ownership of the drug;
function changecurrentownership (bytes32 newName, bytes32 oldName,address payable oldAddress, address payable newAddress,address payable _jushandedoveraddress,address payable manufactureraddress, bytes32 _RFID, uint e, bool haspackage, uint f, uint256 _currentownerprocessingfee) public {
uint256 _nonce;
bytes memory _signature;
procent.currentownerscount =e;
me.numOfDrugCount = f;
uint w = me.numOfDrugCount;
me.drugs[me.RFID][w].manufacturer =manufactureraddress;
me.drugs[me.RFID][w].RFID = _RFID;
i =procent.currentownerscount;
processingstructures.currentpersoncount =e;
strucount =processingstructures.currentpersoncount;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].hasdrug = haspackage;
uint _escrowvictimmoney;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].justhandedoveraddres =_jushandedoveraddress;
//Here is where we check to see if the mesage sender is really the person
//Here we have to add the drug, because the drug has to literally change hands;
if (msg.sender != procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner &&processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].hasdrug==true) return;//This is optional
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].hasdrug=false;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownername = oldName;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner= oldAddress;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownerprocessingfee = _currentownerprocessingfee;
procent.processingentities[procent.RFIDofdrugtobesent][i].receivername= newName;
procent.processingentities[procent.RFIDofdrugtobesent][i].receiver= newAddress;
EscrowComplianceCecker.claimPayment( procent.processingentities[procent.RFIDofdrugtobesent][i].currentownerprocessingfee,_nonce,_signature, procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner);
procent.processingentities[procent.RFIDofdrugtobesent][i].balance+= procent.processingentities[procent.RFIDofdrugtobesent][i].currentownerprocessingfee;
EscrowComplianceCecker.returnbackescrow ( procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner, procent.processingentities[procent.RFIDofdrugtobesent][i].currentownername, _escrowvictimmoney);
procent.processingentities[procent.RFIDofdrugtobesent][i].balance+=_escrowvictimmoney ;
// returnbackescrow (procent[i].currentowner, procent[i].currentownername);
//LASTOWNER WILL BE PAID HERE
procent.processingentities[procent.RFIDofdrugtobesent][i].currentownername= procent.processingentities[procent.RFIDofdrugtobesent][i].receivername ;
procent.processingentities[procent.RFIDofdrugtobesent][i].currentowner = procent.processingentities[procent.RFIDofdrugtobesent][i].receiver;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].justhandedoveraddres = msg.sender;
procent.processingentities[procent.RFIDofdrugtobesent][i].RFIDofdrugtobesent = me.drugs[me.RFID][w].RFID ;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].manufacturerofdrugstobesent = me.drugs[me.RFID][w].manufacturer;
processingstructures.ProcessingEntityStructures[processingstructures.RFIDofthisdrug][strucount].hasdrug = true;
//This is optional
}
}
contract Consumer is EscrowComplianceCecker {
uint i;
struct Buyer {
bytes32 customername;
uint customerage;
uint price;
uint thecustomerscount;
address payable consumeraddress;
bytes32 RFIDS;
mapping (address => Buyer[]) buyers;
mapping (bytes32 => Buyer[]) somebuyer;
}
Buyer[] public consumerstore;
Buyer consumer;
function getConsumerdetails(address payable _consumeraddress) public returns(address payable consumeraddressretrieved, bytes32 customerretrievedname, uint customerretrievedage) {
i = consumer.thecustomerscount;
consumer.consumeraddress = _consumeraddress;
consumer.buyers[consumer.consumeraddress][i].consumeraddress = consumer.consumeraddress;
consumer.buyers[consumer.consumeraddress][i].customername =customerretrievedname ;
consumer.buyers[consumer.consumeraddress][i].customerage;
require( consumer.buyers[consumer.consumeraddress][i].consumeraddress == consumer.consumeraddress);
return ( consumer.buyers[consumer.consumeraddress][i].consumeraddress,consumer.buyers[consumer.consumeraddress][i].customername,
consumer.buyers[consumer.consumeraddress][i].customerage
);
}
function storeconsumerstuff(address payable _consumeraddresses, bytes32 _customernamess, uint _customeragess, uint priceshere, bytes32 RRFIDS ) public {
i = consumer.thecustomerscount++;
consumer.consumeraddress = _consumeraddresses;
consumer.customername = _customernamess;
consumer.customerage = _customeragess;
consumer.price =priceshere;
consumer.RFIDS =RRFIDS;
consumer.somebuyer[consumer.RFIDS][i].consumeraddress = consumer.consumeraddress;
consumer.somebuyer[ consumer.RFIDS][i].customername = consumer.customername;
consumer.somebuyer[ consumer.RFIDS][i].customerage =consumer.customerage;
consumer.somebuyer[ consumer.RFIDS][i].price =priceshere;
consumer.somebuyer[ consumer.RFIDS][i].RFIDS= RRFIDS;
consumerstore.push(Buyer(
{
customername: consumer.somebuyer[ consumer.RFIDS][i].customername,
customerage: consumer.somebuyer[ consumer.RFIDS][i].customerage,
price: consumer.somebuyer[consumer.RFIDS][i].price,
thecustomerscount: consumer.somebuyer[consumer.RFIDS][i].thecustomerscount,
consumeraddress: consumer.somebuyer[consumer.RFIDS][i].consumeraddress,
RFIDS: consumer.somebuyer[ consumer.RFIDS][i].RFIDS
}));
}
function drugbought(address payable _consumeraddr, bytes32 _customernam, bytes32 drugsRFID ) public returns (address payable suchacustomer, bytes32 customername, bytes32 thedrugandRFID, uint priceofdrug) {
i = consumer. thecustomerscount++;
consumer.consumeraddress = _consumeraddr;
consumer.customername = _customernam;
consumer.price;
consumer.RFIDS =drugsRFID;
consumer.somebuyer[ consumer.RFIDS][i].consumeraddress;
consumer.somebuyer[ consumer.RFIDS][i].customername ;
consumer.somebuyer[ consumer.RFIDS][i].price;
consumer.somebuyer[ consumer.RFIDS][i].RFIDS;
require(consumer.buyers[consumer.consumeraddress][i].consumeraddress == consumer.consumeraddress || consumer.somebuyer[ consumer.RFIDS][i].RFIDS ==consumer.RFIDS);
return ( consumer.buyers[consumer.consumeraddress][i].consumeraddress, consumer.somebuyer[ consumer.RFIDS][i].customername , consumer.somebuyer[ consumer.RFIDS][i].RFIDS, consumer.somebuyer[ consumer.RFIDS][i].price
);
}
function verify(bytes32 _RFID) public{
uint vry;
Industry industrye = Industry(vry);
industrye.PrintthemAll(_RFID);
}
function sendescrow(address payable escrowparticipator, bytes32 escrowparticipatorname, uint escrowparticipatoramount) public {
EscrowComplianceCecker.sendescrow( escrowparticipator, escrowparticipatorname, escrowparticipatoramount);
}
function returnbackescrow (address payable _escrowvictimaddress, bytes32 _escrowvictimmame, uint _escrowvictimmoney) public{
EscrowComplianceCecker.returnbackescrow( _escrowvictimaddress, _escrowvictimmame, _escrowvictimmoney) ;
}
function deposit(address payable donator, address payable receipient, uint amount) public payable {
EscrowComplianceCecker.deposit( donator, receipient, amount);
}
function withdraw(uint balanceamount, uint escrowbalancenow) public payable {
EscrowComplianceCecker.withdraw(balanceamount,escrowbalancenow);
}
function balances() public view returns(uint) {
EscrowComplianceCecker.balances();
}
function claimPayment( uint256 amount, uint256 nonce, bytes memory signature,address payable receipientaddress)
public {
EscrowComplianceCecker.claimPayment(amount, nonce, signature, receipientaddress);
}
}
//#SignedByGod
| / knownEntity[entityAddress];(entityStructs[rowNumber].entityAddress != entityAddress; | function sendescrow(address payable escrowparticipator, bytes32 escrowparticipatorname, uint escrowparticipatoramount) public {
escrowobtainee.escrowobtainees;
escrowobtainee.escrowparticipantcount;
m =escrowobtainee.escrowparticipantcount;
uint obtcounter = m++;
escrowobtainee.escrowparticipantaddress= escrowparticipator;
escrowobtainee.escrowparticipantname=escrowparticipatorname;
require(amountrequired <= escrowparticipatoramount, "This is not enough for escrow");
escrowobtainee.escrowparticipantsinitialamountputin =escrowparticipatoramount;
uint escrowedvaluesent = escrowobtainee.escrowparticipantsinitialamountputin;
escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantsinitialamountputin =escrowedvaluesent;
escrowbalance += escrowobtainee.escrowparticipantsinitialamountputin;
proposals.push(EscrowComplianceCecker.EscrowObtained({
escrowparticipantaddress: escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantaddress,
escrowparticipantname:escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantname,
escrowparticipantsinitialamountputin:escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantsinitialamountputin,
escrowparticipanttimestamp:escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipanttimestamp,
escrowparticipantcount:escrowobtainee.escrowobtainees[escrowparticipator][obtcounter].escrowparticipantcount
}));
}
| 6,419,753 |
pragma solidity ^0.6.0;
contract initializable5 { //inject NONSTANDARD NAMING
bool private initialized;
bool private initializing;
modifier INITIALIZER65() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
}
function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING
}
function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA22() 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;
}
uint256[50] private __gap;
}
contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
__OWNABLE_INIT_UNCHAINED84();
}
function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER78();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED52(address(0), msgSender);
}
function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER81() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED52(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED52(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
library safemath14 { //inject NONSTANDARD NAMING
function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB60(a, b, "SafeMath: subtraction overflow");
}
function SUB60(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 MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV54(a, b, "SafeMath: division by zero");
}
function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD56(a, b, "SafeMath: modulo by zero");
}
function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface ierc2086 { //inject NONSTANDARD NAMING
function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library console87 { //inject NONSTANDARD NAMING
address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address36;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG40() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log()"));
}
function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOG40(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
interface iuniswapv2factory11 { //inject NONSTANDARD NAMING
event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO47() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO7(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING
}
contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING
using safemath14 for uint256;
function INITIALIZE58( //inject NONSTANDARD NAMING
address _NANOCOREAddress,
address _WETHAddress,
address _uniswapFactory
) public INITIALIZER65 {
ownableupgradesafe25.__OWNABLE_INIT13();
nanocoreTokenAddress = _NANOCOREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress);
feePercentX100 = 15;
paused = false; // We start paused until sync post LGE happens.
}
address tokenUniswapPair;
iuniswapv2factory11 public uniswapFactory;
address internal WETHAddress;
address nanocoreTokenAddress;
address nanocoreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
// Pausing transfers of the token
function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING
paused = _pause;
}
function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING
feePercentX100 = _feeMultiplier;
}
function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING
nanocoreVaultAddress = _nanocoreVaultAddress;
}
function SYNC99() public { //inject NONSTANDARD NAMING
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
// console.log("sender is " , sender);
// console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair);
// console.log("Old LP supply", lastTotalSupplyOfLPTokens);
// console.log("Current LP supply", _LPSupplyOfPairTotal);
if(sender == tokenUniswapPair)
require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden");
// console.log('Sender is pair' , sender == tokenUniswapPair);
// console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop
console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console87.LOG40("Normal fee transfer");
transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000);
transferToAmount = amount.SUB60(transferToFeeDistributorAmount);
}
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
} | inject NONSTANDARD NAMING | function LOG40(uint p0, address p1, string memory p2, address p3) internal view { | 1,019,015 |
./full_match/137/0xD810f8aBA4EB626d13F0BAF2C9f5b0e2AF8e6351/sources/contracts/masterchef.sol | Add a new lp to the pool. Can only be called by the owner. | function add(uint256 _allocPoint, IERC20 _lpToken, uint16 _depositFeeBP) external onlyOwner nonDuplicated(_lpToken) {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolExistence[_lpToken] = true;
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCSWAPPerShare: 0,
depositFeeBP: _depositFeeBP
}));
}
| 4,685,443 |
./full_match/5/0x62dD98AE09954873EF18Cb47E0879D637512D497/sources/contracts/CrowdFunding.sol | now we have to loop through every campaign and populate that variable.This can be useful for manipulating the data in the Campaign object without modifying the original object in the array. | function getCampaigns() view public returns (Campaign[] memory) {
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for(uint i = 0; i < numberOfCampaigns; i++) {
Campaign storage item = campaigns[i];
allCampaigns[i] = item;
}
return allCampaigns;
}
| 7,040,739 |
./partial_match/1/0x640f7B78830db57BAfDF6F462d2B458dA80825D3/sources/contracts/protocol/leverage/GeneralLevSwap.sol | _principal - The amount of collateral _leverage - Extra leverage value and must be greater than 0, ex. 300% = 300_00 _principal + _principal _leverage should be used as collateral _borrowAsset - The borrowing asset address when leverage works _flashLoanType - 0 is Aave, 1 is Balancer _swapInfo - The uniswap/balancer swap paths between borrowAsset and collateral/ | function enterPositionWithFlashloan(
uint256 _principal,
uint256 _leverage,
address _borrowAsset,
IGeneralLevSwap.FlashLoanType _flashLoanType,
IGeneralLevSwap.SwapInfo calldata _swapInfo
) external nonReentrant {
require(_principal != 0, Errors.LS_SWAP_AMOUNT_NOT_GT_0);
require(_leverage != 0, Errors.LS_SWAP_AMOUNT_NOT_GT_0);
require(_leverage < 900_00, Errors.LS_INVALID_CONFIGURATION);
require(_borrowAsset != address(0), Errors.LS_INVALID_CONFIGURATION);
require(ENABLED_BORROW_ASSETS[_borrowAsset], Errors.LS_STABLE_COIN_NOT_SUPPORTED);
require(IERC20(COLLATERAL).balanceOf(msg.sender) >= _principal, Errors.LS_SUPPLY_NOT_ALLOWED);
IERC20(COLLATERAL).safeTransferFrom(msg.sender, address(this), _principal);
_leverageWithFlashloan(
IGeneralLevSwap.LeverageParams(
msg.sender,
_principal,
_leverage,
_borrowAsset,
_flashLoanType,
_swapInfo
)
);
}
| 15,492,423 |
./full_match/4/0xb19D68085FF3078e1f9911cc2509c4aFB6d40be1/sources/contracts/RootChainManager.sol | payable(typeToPredicate[tokenToType[ETHER_ADDRESS]]).transfer(msg.value); transfer doesn't work as expected when receiving contract is proxified so using call | function _depositEtherFor(address user) private {
bytes memory depositData = abi.encode(msg.value);
ITokenPredicate(ethPredicateAddress).lockTokens(
_msgSender(),
user,
address(0),
depositData
);
if (!success) {
revert("RootChainManager: ETHER_TRANSFER_FAILED");
}
}
| 12,416,595 |
pragma solidity ^0.4.11;
import "zeppelin-solidity/contracts/math/SafeMath.sol";
import "./crowdsale/CappedCrowdsale.sol";
import "./crowdsale/RefundableCrowdsale.sol";
import './Dagt.sol';
//contract DagtCrowdSale is CappedCrowdsale, RefundableCrowdsale {
contract DagtCrowdSale is Dagt,CappedCrowdsale, RefundableCrowdsale {
// DAGT token unit.
// Using same decimal value as ETH (makes ETH-DAGT conversion much easier).
// This is the same as in DAGT token contract.
uint256 public constant TOKEN_UNIT = 10 ** 18;
// Maximum number of tokens in circulation
uint256 public constant MAX_TOKENS = 100000000 * TOKEN_UNIT;
uint256 public constant LOCK_NUMS_SUPPLY = 20000000;
// new rates
//折扣值区块高度范围
uint256[] private blocksRanges;
uint[] private rates;
// 奖励区块高度范围:[0]...[1]
uint256[] private rewardBlocksHeight = new uint256[](2);
//5%
uint[] private rewardRates;
//200-299
uint[] private extraRewardRanges;
//1ETH = 1118DAGT
uint256 public constant DAGTEXCHANGE = 1118;
// Cap per tier for bonus in wei.
uint256 public constant TIER1 = 3000 * TOKEN_UNIT;
uint256 public constant TIER2 = 5000 * TOKEN_UNIT;
uint256 public constant TIER3 = 7500 * TOKEN_UNIT;
//white listed address
mapping (address => bool) public whiteListedAddress;
mapping (address => bool) public whiteListedAddressPresale;
uint256 private _startBlock = 2845788;
uint256 private _endBlock = 3845788;
uint256 private _goal = 20000000000000000000000000;
uint256 private _cap =20000000000000000000000000;
address private _wallet;
address compAddress;
address teamAddress;
struct TransOrder {
uint256 totalDAGTNums;
uint transCount;//转账计数 0.第一个月...4.第五个月 大于四已经转完
}
mapping (address=> mapping(uint => TransOrder)) private DAGTlist;
mapping (address => uint) personBuyTimes;
// mapping (address => LockNumPerson) DAGTlist;
//2845788, 4845788, 20000000000000000000000000, 20000000000000000000000000, 100000000000000000000000000, "0x627306090abaB3A6e1400e9345bC60c78a8BEf57"
function DagtCrowdSale ()
CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startBlock, _endBlock, _wallet) public {
require(_goal <= _cap);
require(_endBlock > _startBlock);
startBlock = _startBlock;
endBlock = _endBlock;
wallet =_wallet;
totalSupply_ = 100000000 * TOKEN_UNIT;
///////////////////
}
function createTokenContract() internal returns (MintableToken) {
return new Dagt();
}
modifier onlyWhitelisted() {
require( isWhitelisted(msg.sender)) ;
_;
}
/**
* @dev Add a list of address to be whitelisted for the crowdsale only.
* @param _users , the list of user Address. Tested for out of gas until 200 addresses.
*/
function whitelistAddresses( address[] _users) public onlyOwner {
for( uint i = 0 ; i < _users.length ; i++ ) {
whiteListedAddress[_users[i]] = true;
}
}
function unwhitelistAddress( address _users) public onlyOwner {
whiteListedAddress[_users] = false;
}
function isWhitelisted(address _user) public constant returns (bool) {
return whiteListedAddress[_user];
}
function () public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable onlyWhitelisted {
require(beneficiary != 0x0);
//require(validPurchase());
uint256 rate=getETH2DAGTRate();
uint256 weiAmount = msg.value;
require(weiAmount > 0);
uint256 ethAmount = weiAmount.div(1000000000000000000);
uint256 tokensDAGT = ethAmount.mul(rate);
uint buyNo =personBuyTimes[beneficiary];
DAGTlist[beneficiary][buyNo].totalDAGTNums = tokensDAGT;
rate =amountReward(tokensDAGT);
uint256 transDagts =tokensDAGT.mul(20).div(100);
if(DAGTlist[beneficiary][buyNo].transCount==0)
{
transDagts = transDagts.add(rate);
}
bool ret = super.transferFrom(compAddress,beneficiary,transDagts);//ret = token.mint(beneficiary, transDagts);
if(ret==true)
{
DAGTlist[beneficiary][buyNo].transCount = 1;
}
personBuyTimes[beneficiary] = buyNo.add(1);
TokenPurchase(msg.sender, beneficiary, weiAmount, transDagts);
forwardFunds();
}
//锁仓后每月转账接口
function transDagt(address _to,uint buyNo) public returns(bool success) {
bool ret=false;
require(_to != 0x0);
uint256 trans_Value =0;
if( (buyNo>0 && buyNo<5) && (DAGTlist[_to][buyNo].totalDAGTNums>0))
{
trans_Value =DAGTlist[_to][buyNo].totalDAGTNums.mul(20).div(100);
}
ret = super.transferFrom(compAddress,_to,trans_Value);
TokenPurchase(msg.sender, _to, 0, trans_Value);
if(ret == true)
{
DAGTlist[_to][buyNo].transCount = DAGTlist[_to][buyNo].transCount.add(1);
}
return ret;
}
//设置开始 结束区块高度及折扣值,以便计算ETH折扣DAGT
function setBlocksRate(uint256[] _blocksRanges,uint256[] _rates) public{
require(_blocksRanges.length >=2);
require(_blocksRanges.length == _rates.length.mul(2));
blocksRanges = new uint256[](_blocksRanges.length);
rates = new uint[](_rates.length);
blocksRanges = _blocksRanges;
rates = _rates;
/* for( uint i = 0 ; i < _startBlocks.length ; i++ )
{
blocksRateStart[i] = _startBlocks[i];
blocksRateEnd[i] = _endBlocks[i];
rates[i] = _rates[i];
}*/
}
//通过时间转换成区块高度,取得ETH折扣DAGT
function getETH2DAGTRate() private view returns (uint256 rate) {
uint blockHight = block.number;
rate = 0;
uint idx =0;
for( uint i = 0 ; i < blocksRanges.length ; i+=2)
{
if((blockHight>blocksRanges[i]) && (blockHight<=blocksRanges[i+1]) )
{
rate = rates[idx];
idx++;
}
}
return rate;
}
//
function setRewardRange(uint256[] _blocksNums, uint[] _extraRewardRanges, uint[] _rewards) public{
rewardBlocksHeight = new uint256[](_blocksNums.length);
extraRewardRanges = new uint256[](_extraRewardRanges.length);
rewardRates = new uint256[](_rewards.length);
rewardBlocksHeight = _blocksNums;
extraRewardRanges =_extraRewardRanges;
rewardRates = _rewards;
}
function amountReward(uint256 dagts) private view returns (uint256 rewardDagts) {
rewardDagts=0;
uint256 blockHight = block.number;
if((blockHight>=rewardBlocksHeight[0]) && (blockHight<=rewardBlocksHeight[1]) )
{
uint idx =0;
for(uint i =0;i<extraRewardRanges.length;i=i+2)
{
if(dagts>=DAGTEXCHANGE.mul(extraRewardRanges[i]) && dagts<=DAGTEXCHANGE.mul(extraRewardRanges[i+1]))
{
rewardDagts=(dagts.mul(rewardRates[idx])).div(100);
idx++;
}
}
}
}
function finalization() internal {
if (goalReached()) {
//DAGT gets 20% of the amount of the total token supply
uint256 totalSupply = token.totalSupply();
// total supply
token.mint(wallet, MAX_TOKENS.sub(totalSupply));
token.finishMinting();
}
super.finalization();
}
}
| Add a list of address to be whitelisted for the crowdsale only. _users , the list of user Address. Tested for out of gas until 200 addresses./ | function whitelistAddresses( address[] _users) public onlyOwner {
for( uint i = 0 ; i < _users.length ; i++ ) {
whiteListedAddress[_users[i]] = true;
}
}
| 901,442 |
pragma solidity >=0.4.15;
import './Common.sol';
contract ERC20Interface {
function getTotalSupply() public returns (uint totalSupply);
function getTokenBalance(address _owner) public constant returns (uint balance);
function mint(address _addr, uint _amount) public;
function burn(uint _amount) public returns (bool result);
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 increaseApproval (address _spender, uint _addedValue) public returns (bool success);
function decreaseApproval (address _spender, uint _subtractedValue) 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);
event Mint(address owner, uint amount);
event Burn(address burner, uint amount);
}
contract Token is ERC20Interface, SafeMath, Owned, Constants {
uint public totalSupply;
address ico;
address controller;
string public name;
uint public decimals;
string public symbol;
//must set the address of the coinbase of contracts and benificiary account as both are same here
address private tokenContractCoinbase = 0x0270a33e6ac28b8c1d444bb5eab3ad1d453e4d5f;
function Token() public {
owner = msg.sender;
// totalSupply = 100000000000000000000000;
// balanceOf[owner] = totalSupply;
owner = msg.sender;
name = "Custom Token";
decimals = uint(DECIMALS);
symbol = "CT";
}
function getTotalSupply() public returns (uint) {
return totalSupply;
}
function getTokenBalance(address _a) public constant returns (uint) {
return balanceOf[_a];
}
//only called from contracts so don't need msg.data.length check
function mint(address _addr, uint _amount) public {
if (maxSupply > 0 && safeAdd(totalSupply, _amount) > maxSupply)
revert();
// Check for overflows
require(balanceOf[_addr] + _amount > balanceOf[_addr]);
balanceOf[_addr] = safeAdd(balanceOf[_addr], _amount);
totalSupply = safeAdd(totalSupply, _amount);
//updating the maxSupply to new reduced value
maxSupply = safeSub(maxSupply, _amount);
Mint(_addr, _amount);
}
mapping(address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
//for avoiding under flow
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
}
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
function transfer(address _to, uint _value)
onlyPayloadSize(2)
public returns (bool success)
{
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value)
onlyPayloadSize(3)
public returns (bool success)
{
if (balanceOf[_from] < _value)
return false;
var allowed = allowance[_from][msg.sender];
if (allowed < _value)
return false;
allowance[_from][msg.sender] = safeSub(allowed, _value);
_transfer(_from, _to, _value);
return true;
}
modifier notTokenCoinbase(address _from) {
require (_from != tokenContractCoinbase);
_;
}
function sendTokens(address _from, address _to, uint _value)
onlyPayloadSize(3)
notTokenCoinbase(_from)
public returns (bool success)
{
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value)
onlyPayloadSize(2)
public returns (bool success)
{
//require user to set to zero before resetting to nonzero
if ((_value != 0) && (allowance[msg.sender][_spender] != 0)) {
return false;
}
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
onlyPayloadSize(2)
constant
public returns (uint remaining) {
return allowance[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue)
onlyPayloadSize(2)
public returns (bool success)
{
uint oldValue = allowance[msg.sender][_spender];
allowance[msg.sender][_spender] = safeAdd(oldValue, _addedValue);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
onlyPayloadSize(2)
public returns (bool success)
{
uint oldValue = allowance[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowance[msg.sender][_spender] = 0;
} else {
allowance[msg.sender][_spender] = safeSub(oldValue, _subtractedValue);
}
return true;
}
function burn(uint _amount) public returns (bool result) {
//for avoiding under flow
if (_amount > balanceOf[msg.sender])
return false;
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _amount);
totalSupply = safeSub(totalSupply, _amount);
//updating the maxSupply to new reduced value
maxSupply = safeAdd(maxSupply, _amount);
Burn(msg.sender, _amount);
return true;
}
bool public flag = false;
modifier onlyOnce() {
if (flag == true)
revert();
_;
}
uint public maxSupply;
function setMaxSupply(uint _maxSupply)
onlyOnce
public {
if (maxSupply > 0)
revert();
maxSupply = _maxSupply;
flag = true;
}
} | only called from contracts so don't need msg.data.length check Check for overflowsupdating the maxSupply to new reduced value | function mint(address _addr, uint _amount) public {
if (maxSupply > 0 && safeAdd(totalSupply, _amount) > maxSupply)
revert();
require(balanceOf[_addr] + _amount > balanceOf[_addr]);
balanceOf[_addr] = safeAdd(balanceOf[_addr], _amount);
totalSupply = safeAdd(totalSupply, _amount);
maxSupply = safeSub(maxSupply, _amount);
Mint(_addr, _amount);
}
mapping(address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
| 13,130,071 |
/**
*Submitted for verification at Etherscan.io on 2022-02-09
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
interface IERC20{
function name() external view returns(string memory);
function symbol() external view returns(string memory);
function totalSupply() external view returns (uint );
function decimals() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function approve(address sender , uint value)external returns(bool);
function allowance(address sender, address spender) external view returns (uint256);
function transfer(address recepient , uint value) external returns(bool);
function transferFrom(address sender,address recepient, uint value) external returns(bool);
event Transfer(address indexed from , address indexed to , uint value);
event Approval(address indexed sender , address indexed spender , uint 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 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{
constructor () {}
function _msgsender() internal view returns (address) {
return msg.sender;
}
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
library safeMath{
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint a , uint b) internal pure returns(uint){
uint c = a+ b;
require(c >= a, "amount exists");
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint a , uint b , string memory errorMessage) internal pure returns(uint){
uint c = a - b;
require( c <= a , errorMessage );
return c;
}
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on 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;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/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.
*/
contract Ownable is Context{
address private _Owner;
event transferOwnerShip(address indexed _previousOwner , address indexed _newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor(){
address msgsender = _msgsender();
_Owner = msgsender;
emit transferOwnerShip(address(0),msgsender);
}
/**
* @dev Returns the address of the current owner.
*/
function checkOwner() 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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address _newOwner) public OnlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0),"Owner should not be 0 address");
emit transferOwnerShip(_Owner,_newOwner);
_Owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract LiquidblockToken is Context, IERC20, Ownable {
using safeMath for uint;
mapping(address => uint) _balances;
mapping(address => mapping(address => uint)) _allowances;
string private _name;
string private _symbol;
uint private _decimal;
uint private _totalSupply;
constructor(){
_name = "Liquidblock";
_symbol = "LQB";
_decimal = 18;
_totalSupply = 100000000*10**18;
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
/**
* @return the name of the token.
*/
function name() external override view returns(string memory){
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() external view override returns(string memory){
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() external view override returns(uint){
return _decimal;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) external view override returns(uint){
return _balances[owner];
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() external view override returns(uint){
return _totalSupply;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender , uint value) external override returns(bool){
_approve(_msgsender(), spender , value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param sender address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address sender , address spender) external view override returns(uint){
return _allowances[sender][spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgsender(), spender, _allowances[_msgsender()][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgsender(), spender, _allowances[_msgsender()][spender].sub(subtractedValue, "LQB: decreased allowance below zero"));
return true;
}
/**
* @dev Transfer token for a specified address
* @param recepient The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address recepient , uint value) external override returns(bool){
_transfer(msg.sender, recepient,value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param sender address The address which you want to send tokens from
* @param recepient address The address which you want to transfer to
* @param amount uint256 the amount of tokens to be transferred
*/
function transferFrom(address sender ,address recepient, uint amount) external override returns(bool){
_approve(sender, _msgsender(), _allowances[sender][_msgsender()].sub(amount,"exceeds allownace"));
_transfer(sender,recepient,amount);
return true;
}
/**
* @dev Burns token balance in "account" and decrease totalsupply of token
* Can only be called by the current owner.
*/
function burn(uint256 amount) public OnlyOwner returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param sender The address to transfer from.
* @param recepient The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address sender,address recepient, uint value) internal returns(bool success){
require(_balances[sender] >= value,"Balance not enough");
_balances[sender] = _balances[sender].sub(value,"Exceeds balance");
_balances[recepient] = _balances[recepient].add(value);
emit Transfer(_msgsender(), recepient , value);
return true;
}
/**
* @dev Approve token for a specified addresses
* @param sender The address to transfer from.
* @param spender The address to transfer to.
* @param amount The amount to be transferred.
*/
function _approve(address sender,address spender, uint amount) internal returns(bool success){
require(sender != address(0),"Should not be 0 address");
require(spender != address(0),"Should not be zero address");
_allowances[sender][spender] = amount;
emit Approval(sender, spender, amount);
return true;
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), " LQB: burn from the zero address");
_balances[account] = _balances[account].sub(amount, " LQB: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount,"cant burn");
emit Transfer(account, address(0), amount);
}
} | Transfer tokens from one address to another. Note that while this function emits an Approval event, this is not required as per the specification, and other compliant implementations may not emit the event. sender address The address which you want to send tokens from recepient address The address which you want to transfer to amount uint256 the amount of tokens to be transferred/ | function transferFrom(address sender ,address recepient, uint amount) external override returns(bool){
_approve(sender, _msgsender(), _allowances[sender][_msgsender()].sub(amount,"exceeds allownace"));
_transfer(sender,recepient,amount);
return true;
}
| 10,585,187 |
/**
*Submitted for verification at Etherscan.io on 2021-05-17
*/
// File: contracts/interface/ICoFiXV2DAO.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
interface ICoFiXV2DAO {
function setGovernance(address gov) external;
function start() external;
// function addETHReward() external payable;
event FlagSet(address gov, uint256 flag);
event CoFiBurn(address gov, uint256 amount);
}
// File: contracts/lib/TransferHelper.sol
pragma solidity 0.6.12;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interface/IWETH.sol
pragma solidity 0.6.12;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
function balanceOf(address account) external view returns (uint);
}
// File: contracts/interface/ICoFiXERC20.sol
pragma solidity 0.6.12;
interface ICoFiXERC20 {
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;
}
// File: contracts/interface/ICoFiXV2Pair.sol
pragma solidity 0.6.12;
interface ICoFiXV2Pair is ICoFiXERC20 {
struct OraclePrice {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 theta;
}
// All pairs: {ETH <-> ERC20 Token}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
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);
function mint(address to, uint amountETH, uint amountToken) external payable returns (uint liquidity, uint oracleFeeChange);
function burn(address tokenTo, address ethTo) external payable returns (uint amountTokenOut, uint amountETHOut, uint oracleFeeChange);
function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[5] memory tradeInfo);
// function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function skim(address to) external;
function sync() external;
function initialize(address, address, string memory, string memory, uint256, uint256) external;
/// @dev get Net Asset Value Per Share
/// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token}
/// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token}
/// @return navps The Net Asset Value Per Share (liquidity) represents
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps);
/// @dev get initial asset ratio
/// @return _initToken0Amount Token0(ETH) side of initial asset ratio {ETH <-> ERC20 Token}
/// @return _initToken1Amount Token1(ERC20) side of initial asset ratio {ETH <-> ERC20 Token}
function getInitialAssetRatio() external view returns (uint256 _initToken0Amount, uint256 _initToken1Amount);
}
// File: contracts/CoFiXERC20.sol
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
// ERC20 token implementation, inherited by CoFiXPair contract, no owner or governance
contract CoFiXERC20 is ICoFiXERC20 {
using SafeMath for uint;
string public constant nameForDomain = 'CoFiX Pool Token';
uint8 public override constant decimals = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public override nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(nameForDomain)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(deadline >= block.timestamp, 'CERC20: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'CERC20: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// File: contracts/CoFiXV2Pair.sol
pragma solidity 0.6.12;
// Pair contract for each trading pair, storing assets and handling settlement
// No owner or governance
contract CoFiXV2Pair is ICoFiXV2Pair, CoFiXERC20 {
using SafeMath for uint;
enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX
uint public override constant MINIMUM_LIQUIDITY = 10**9; // it's negligible because we calc liquidity in ETH
bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
uint256 constant public K_BASE = 1E8; // K
uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy
uint256 constant public THETA_BASE = 1E8; // theta
string public name;
string public symbol;
address public override immutable factory;
address public override token0; // WETH token
address public override token1; // any ERC20 token
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint256 public initToken1Amount;
uint256 public initToken0Amount;
uint private unlocked = 1;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
modifier lock() {
require(unlocked == 1, "CPair: LOCKED");
unlocked = 0;
_;
unlocked = 1;
}
constructor() public {
factory = msg.sender;
}
receive() external payable {}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1, string memory _name, string memory _symbol, uint256 _initToken0Amount, uint256 _initToken1Amount) external override {
require(msg.sender == factory, "CPair: FORBIDDEN"); // sufficient check
token0 = _token0;
token1 = _token1;
name = _name;
symbol = _symbol;
initToken1Amount = _initToken1Amount;
initToken0Amount = _initToken0Amount;
}
function getInitialAssetRatio() public override view returns (uint256 _initToken0Amount, uint256 _initToken1Amount) {
_initToken1Amount = initToken1Amount;
_initToken0Amount = initToken0Amount;
}
function getReserves() public override view returns (uint112 _reserve0, uint112 _reserve1) {
_reserve0 = reserve0;
_reserve1 = reserve1;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "CPair: TRANSFER_FAILED");
}
// update reserves
function _update(uint balance0, uint balance1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), "CPair: OVERFLOW");
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
emit Sync(reserve0, reserve1);
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to, uint amountETH, uint amountToken) external payable override lock returns (uint liquidity, uint oracleFeeChange) {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
(uint112 _reserve0, uint112 _reserve1) = getReserves(); // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
require(amountETH <= amount0 && amountToken <= amount1, "CPair: illegal ammount");
amount0 = amountETH;
amount1 = amountToken;
require(amount0.mul(initToken1Amount) == amount1.mul(initToken0Amount), "CPair: invalid asset ratio");
uint256 _ethBalanceBefore = address(this).balance;
{ // scope for ethAmount/erc20Amount/blockNum to avoid stack too deep error
bytes memory data = abi.encode(msg.sender, to, amount0, amount1);
// query price
OraclePrice memory _op;
(_op.K, _op.ethAmount, _op.erc20Amount, _op.blockNum, _op.theta) = _queryOracle(_token1, CoFiX_OP.MINT, data);
uint256 navps = calcNAVPerShare(_reserve0, _reserve1, _op.ethAmount, _op.erc20Amount);
if (totalSupply == 0) {
liquidity = calcLiquidity(amount0, navps).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = calcLiquidity(amount0, navps);
}
}
oracleFeeChange = msg.value.sub(_ethBalanceBefore.sub(address(this).balance));
require(liquidity > 0, "CPair: SHORT_LIQUIDITY_MINTED");
_mint(to, liquidity);
_update(balance0, balance1);
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address tokenTo, address ethTo) external payable override lock returns (uint amountTokenOut, uint amountEthOut, uint oracleFeeChange) {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
uint256 _ethBalanceBefore = address(this).balance;
// uint256 fee;
{
bytes memory data = abi.encode(msg.sender, liquidity);
// query price
OraclePrice memory _op;
(_op.K, _op.ethAmount, _op.erc20Amount, _op.blockNum, _op.theta) = _queryOracle(_token1, CoFiX_OP.BURN, data);
(amountTokenOut, amountEthOut) = calcOutTokenAndETHForBurn(liquidity, _op); // navps calculated
}
oracleFeeChange = msg.value.sub(_ethBalanceBefore.sub(address(this).balance));
require(amountTokenOut > 0 && amountEthOut > 0, "CPair: SHORT_LIQUIDITY_BURNED");
_burn(address(this), liquidity);
_safeTransfer(_token1, tokenTo, amountTokenOut);
_safeTransfer(_token0, ethTo, amountEthOut);
// if (fee > 0) {
// if (ICoFiXV2Factory(factory).getTradeMiningStatus(_token1)) {
// // only transfer fee to protocol feeReceiver when trade mining is enabled for this trading pair
// _safeSendFeeForDAO(_token0, fee);
// } else {
// _safeSendFeeForLP(_token0, _token1, fee);
// }
// }
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1);
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
emit Burn(msg.sender, _token0, amountEthOut, ethTo);
emit Burn(msg.sender, _token1, amountTokenOut, tokenTo);
}
// this low-level function should be called from a contract which performs important safety checks
function swapWithExact(address outToken, address to)
external
payable override lock
returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[5] memory tradeInfo)
{
// tradeInfo[0]: thetaFee, tradeInfo[1]: ethAmount, tradeInfo[2]: erc20Amount
address _token0 = token0;
address _token1 = token1;
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
// uint256 fee;
{ // scope for ethAmount/erc20Amount/blockNum to avoid stack too deep error
uint256 _ethBalanceBefore = address(this).balance;
(uint112 _reserve0, uint112 _reserve1) = getReserves(); // gas savings
// calc amountIn
if (outToken == _token1) {
amountIn = balance0.sub(_reserve0);
} else if (outToken == _token0) {
amountIn = balance1.sub(_reserve1);
} else {
revert("CPair: wrong outToken");
}
require(amountIn > 0, "CPair: wrong amountIn");
bytes memory data = abi.encode(msg.sender, outToken, to, amountIn);
// query price
OraclePrice memory _op;
(_op.K, _op.ethAmount, _op.erc20Amount, _op.blockNum, _op.theta) = _queryOracle(_token1, CoFiX_OP.SWAP_WITH_EXACT, data);
if (outToken == _token1) {
(amountOut, tradeInfo[0]) = calcOutToken1(amountIn, _op);
} else if (outToken == _token0) {
(amountOut, tradeInfo[0]) = calcOutToken0(amountIn, _op);
}
oracleFeeChange = msg.value.sub(_ethBalanceBefore.sub(address(this).balance));
tradeInfo[1] = _op.ethAmount;
tradeInfo[2] = _op.erc20Amount;
}
require(to != _token0 && to != _token1, "CPair: INVALID_TO");
_safeTransfer(outToken, to, amountOut); // optimistically transfer tokens
if (tradeInfo[0] > 0) {
if (ICoFiXV2Factory(factory).getTradeMiningStatus(_token1)) {
// only transfer fee to protocol feeReceiver when trade mining is enabled for this trading pair
_safeSendFeeForDAO(_token0, tradeInfo[0]);
} else {
_safeSendFeeForLP(_token0, _token1, tradeInfo[0]);
tradeInfo[0] = 0; // so router won't go into the trade mining logic (reduce one more call gas cost)
}
}
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1);
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
emit Swap(msg.sender, amountIn, amountOut, outToken, to);
}
// force balances to match reserves
function skim(address to) external override lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external override lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)));
}
// calc Net Asset Value Per Share (no K)
// use it in this contract, for optimized gas usage
function calcNAVPerShare(uint256 balance0, uint256 balance1, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 navps) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
navps = NAVPS_BASE;
} else {
/*
NV = \frac{E_t + U_t/P_t}{(1 + \frac{k_0}{P_t})*F_t}\\\\
= \frac{E_t + U_t * \frac{ethAmount}{erc20Amount}}{(1 + \frac{initToken1Amount}{initToken0Amount} * \frac{ethAmount}{erc20Amount})*F_t}\\\\
= \frac{E_t * erc20Amount + U_t * ethAmount}{(erc20Amount + \frac{initToken1Amount * ethAmount}{initToken0Amount}) * F_t}\\\\
= \frac{E_t * erc20Amount * initToken0Amount + U_t * ethAmount * initToken0Amount}{( erc20Amount * initToken0Amount + initToken1Amount * ethAmount) * F_t} \\\\
= \frac{balance0 * erc20Amount * initToken0Amount + balance1 * ethAmount * initToken0Amount}{(erc20Amount * initToken0Amount + initToken1Amount * ethAmount) * totalSupply}
*/
uint256 balance0MulErc20AmountMulInitToken0Amount = balance0.mul(erc20Amount).mul(initToken0Amount);
uint256 balance1MulEthAmountMulInitToken0Amount = balance1.mul(ethAmount).mul(initToken0Amount);
uint256 initToken1AmountMulEthAmount = initToken1Amount.mul(ethAmount);
uint256 initToken0AmountMulErc20Amount = erc20Amount.mul(initToken0Amount);
navps = (balance0MulErc20AmountMulInitToken0Amount.add(balance1MulEthAmountMulInitToken0Amount))
.div(_totalSupply).mul(NAVPS_BASE)
.div(initToken1AmountMulEthAmount.add(initToken0AmountMulErc20Amount));
}
}
// use it in this contract, for optimized gas usage
function calcLiquidity(uint256 amount0, uint256 navps) public pure returns (uint256 liquidity) {
liquidity = amount0.mul(NAVPS_BASE).div(navps);
}
// get Net Asset Value Per Share for mint
// only for read, could cost more gas if use it directly in contract
function getNAVPerShareForMint(OraclePrice memory _op) public view returns (uint256 navps) {
return calcNAVPerShare(reserve0, reserve1, _op.ethAmount, _op.erc20Amount);
}
// get Net Asset Value Per Share for burn
// only for read, could cost more gas if use it directly in contract
function getNAVPerShareForBurn(OraclePrice memory _op) external view returns (uint256 navps) {
return calcNAVPerShare(reserve0, reserve1, _op.ethAmount, _op.erc20Amount);
}
// get Net Asset Value Per Share
// only for read, could cost more gas if use it directly in contract
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external override view returns (uint256 navps) {
return calcNAVPerShare(reserve0, reserve1, ethAmount, erc20Amount);
}
// get estimated liquidity amount (it represents the amount of pool tokens will be minted if someone provide liquidity to the pool)
// only for read, could cost more gas if use it directly in contract
function getLiquidity(uint256 amount0, OraclePrice memory _op) external view returns (uint256 liquidity) {
uint256 navps = getNAVPerShareForMint(_op);
return calcLiquidity(amount0, navps);
}
function calcOutTokenAndETHForBurn(uint256 liquidity, OraclePrice memory _op) public view returns (uint256 amountTokenOut, uint256 amountEthOut) {
// amountEthOut = liquidity * navps * (THETA_BASE - theta) / THETA_BASE
// amountTokenOut = liquidity * navps * (THETA_BASE - theta) * initToken1Amount / (initToken0Amount * THETA_BASE)
uint256 navps;
{
navps = calcNAVPerShare(reserve0, reserve1, _op.ethAmount, _op.erc20Amount);
uint256 amountEth = liquidity.mul(navps);
uint256 amountEthOutLarge = amountEth.mul(THETA_BASE.sub(_op.theta));
amountEthOut = amountEthOutLarge.div(NAVPS_BASE).div(THETA_BASE);
amountTokenOut = amountEthOutLarge.mul(initToken1Amount).div(NAVPS_BASE).div(initToken0Amount).div(THETA_BASE);
// amountTokenOut = amountEthOut.mul(initToken1Amount).div(initToken0Amount);
}
// recalc amountOut when has no enough reserve0 or reserve1 to out in initAssetRatio
{
if (amountEthOut > reserve0) {
// user first, out eth as much as possibile. And may leave over a few amounts of reserve1.
uint256 amountEthInsufficient = amountEthOut - reserve0;
uint256 amountTokenEquivalent = amountEthInsufficient.mul(_op.erc20Amount).div(_op.ethAmount);
amountTokenOut = amountTokenOut.add(amountTokenEquivalent);
if (amountTokenOut > reserve1) {
amountTokenOut = reserve1;
}
amountEthOut = reserve0;
// amountEthOut = reserve0 - fee;
} else if (amountTokenOut > reserve1) {
uint256 amountTokenInsufficient = amountTokenOut - reserve1;
uint256 amountEthEquivalent = amountTokenInsufficient.mul(_op.ethAmount).div(_op.erc20Amount);
amountEthOut = amountEthOut.add(amountEthEquivalent);
if (amountEthOut > reserve0) {
amountEthOut = reserve0;
}
amountTokenOut = reserve1;
}
}
}
// get estimated amountOut for token0 (WETH) when swapWithExact
function calcOutToken0(uint256 amountIn, OraclePrice memory _op) public pure returns (uint256 amountOut, uint256 fee) {
/*
x &= (a/P_{b}^{'})*\frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= a / (\frac{erc20Amount}{ethAmount} * \frac{(k_{BASE} + k)}{(k_{BASE})}) * \frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= \frac{a*ethAmount*k_{BASE}}{erc20Amount*(k_{BASE} + k)} * \frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= \frac{a*ethAmount*k_{BASE}*(THETA_{BASE} - \theta)}{erc20Amount*(k_{BASE} + k)*THETA_{BASE}} \\\\
// amountOut = amountIn * _op.ethAmount * K_BASE * (THETA_BASE - _op.theta) / _op.erc20Amount / (K_BASE + _op.K) / THETA_BASE;
*/
amountOut = amountIn.mul(_op.ethAmount).mul(K_BASE).mul(THETA_BASE.sub(_op.theta)).div(_op.erc20Amount).div(K_BASE.add(_op.K)).div(THETA_BASE);
if (_op.theta != 0) {
// fee = amountIn * _op.ethAmount * K_BASE * (_op.theta) / _op.erc20Amount / (K_BASE + _op.K) / THETA_BASE;
fee = amountIn.mul(_op.ethAmount).mul(K_BASE).mul(_op.theta).div(_op.erc20Amount).div(K_BASE.add(_op.K)).div(THETA_BASE);
}
return (amountOut, fee);
}
// get estimated amountOut for token1 (ERC20 token) when swapWithExact
function calcOutToken1(uint256 amountIn, OraclePrice memory _op) public pure returns (uint256 amountOut, uint256 fee) {
/*
y &= b*P_{s}^{'}*\frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= b * \frac{erc20Amount}{ethAmount} * \frac{(k_{BASE} - k)}{(k_{BASE})} * \frac{THETA_{BASE} - \theta}{THETA_{BASE}} \\\\
&= \frac{b*erc20Amount*(k_{BASE} - k)*(THETA_{BASE} - \theta)}{ethAmount*k_{BASE}*THETA_{BASE}} \\\\
// amountOut = amountIn * _op.erc20Amount * (K_BASE - _op.K) * (THETA_BASE - _op.theta) / _op.ethAmount / K_BASE / THETA_BASE;
*/
amountOut = amountIn.mul(_op.erc20Amount).mul(K_BASE.sub(_op.K)).mul(THETA_BASE.sub(_op.theta)).div(_op.ethAmount).div(K_BASE).div(THETA_BASE);
if (_op.theta != 0) {
// fee = amountIn * _op.theta / THETA_BASE;
fee = amountIn.mul(_op.theta).div(THETA_BASE);
}
return (amountOut, fee);
}
// get estimate amountInNeeded for token0 (WETH) when swapForExact
function calcInNeededToken0(uint256 amountOut, OraclePrice memory _op) public pure returns (uint256 amountInNeeded, uint256 fee) {
// inverse of calcOutToken1
// amountOut = amountIn.mul(_op.erc20Amount).mul(K_BASE.sub(_op.K)).mul(THETA_BASE.sub(_op.theta)).div(_op.ethAmount).div(K_BASE).div(THETA_BASE);
amountInNeeded = amountOut.mul(_op.ethAmount).mul(K_BASE).mul(THETA_BASE).div(_op.erc20Amount).div(K_BASE.sub(_op.K)).div(THETA_BASE.sub(_op.theta));
if (_op.theta != 0) {
// fee = amountIn * _op.theta / THETA_BASE;
fee = amountInNeeded.mul(_op.theta).div(THETA_BASE);
}
return (amountInNeeded, fee);
}
// get estimate amountInNeeded for token1 (ERC20 token) when swapForExact
function calcInNeededToken1(uint256 amountOut, OraclePrice memory _op) public pure returns (uint256 amountInNeeded, uint256 fee) {
// inverse of calcOutToken0
// amountOut = amountIn.mul(_op.ethAmount).mul(K_BASE).mul(THETA_BASE.sub(_op.theta)).div(_op.erc20Amount).div(K_BASE.add(_op.K)).div(THETA_BASE);
amountInNeeded = amountOut.mul(_op.erc20Amount).mul(K_BASE.add(_op.K)).mul(THETA_BASE).div(_op.ethAmount).div(K_BASE).div(THETA_BASE.sub(_op.theta));
if (_op.theta != 0) {
// fee = amountIn * _op.ethAmount * K_BASE * (_op.theta) / _op.erc20Amount / (K_BASE + _op.K) / THETA_BASE;
fee = amountInNeeded.mul(_op.ethAmount).mul(K_BASE).mul(_op.theta).div(_op.erc20Amount).div(K_BASE.add(_op.K)).div(THETA_BASE);
}
return (amountInNeeded, fee);
}
function _queryOracle(address token, CoFiX_OP op, bytes memory data) internal returns (uint256, uint256, uint256, uint256, uint256) {
return ICoFiXV2Controller(ICoFiXV2Factory(factory).getController()).queryOracle{value: msg.value}(token, uint8(op), data);
}
function _safeSendFeeForDAO(address _token0, uint256 _fee) internal {
address feeReceiver = ICoFiXV2Factory(factory).getFeeReceiver();
if (feeReceiver == address(0)) {
return; // if feeReceiver not set, theta fee keeps in pair pool
}
uint256 bal = IWETH(_token0).balanceOf(address(this));
if (_fee > bal) {
_fee = bal;
}
IWETH(_token0).withdraw(_fee);
if (_fee > 0) TransferHelper.safeTransferETH(feeReceiver, _fee); // transfer fee to protocol dao for redeem Cofi
// ICoFiXV2DAO(dao).addETHReward{value: _fee}();
}
// Safe WETH transfer function, just in case not having enough WETH. LP will earn these fees.
function _safeSendFeeForLP(address _token0, address _token1, uint256 _fee) internal {
address feeVault = ICoFiXV2Factory(factory).getFeeVaultForLP(_token1);
if (feeVault == address(0)) {
return; // if fee vault not set, theta fee keeps in pair pool
}
_safeSendFee(_token0, feeVault, _fee); // transfer fee to protocol fee reward pool for LP
}
function _safeSendFee(address _token0, address _receiver, uint256 _fee) internal {
uint256 wethBal = IERC20(_token0).balanceOf(address(this));
if (_fee > wethBal) {
_fee = wethBal;
}
if (_fee > 0) _safeTransfer(_token0, _receiver, _fee);
}
}
// 🦄 & CoFi Rocks
// File: contracts/interface/ICoFiXV2Controller.sol
pragma solidity 0.6.12;
interface ICoFiXV2Controller {
event NewK(address token, uint256 K, uint256 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum);
event NewGovernance(address _new);
event NewOracle(address _priceOracle);
event NewKTable(address _kTable);
event NewTimespan(uint256 _timeSpan);
event NewKRefreshInterval(uint256 _interval);
event NewKLimit(int128 maxK0);
event NewGamma(int128 _gamma);
event NewTheta(address token, uint32 theta);
event NewK(address token, uint32 k);
event NewCGamma(address token, uint32 gamma);
function addCaller(address caller) external;
function setCGamma(address token, uint32 gamma) external;
function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta);
function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta);
function getLatestPriceAndAvgVola(address token) external payable returns (uint256, uint256, uint256, uint256);
}
// File: contracts/interface/ICoFiXV2Factory.sol
pragma solidity 0.6.12;
interface ICoFiXV2Factory {
// All pairs: {ETH <-> ERC20 Token}
event PairCreated(address indexed token, address pair, uint256);
event NewGovernance(address _new);
event NewController(address _new);
event NewFeeReceiver(address _new);
event NewFeeVaultForLP(address token, address feeVault);
event NewVaultForLP(address _new);
event NewVaultForTrader(address _new);
event NewVaultForCNode(address _new);
event NewDAO(address _new);
/// @dev Create a new token pair for trading
/// @param token the address of token to trade
/// @param initToken0Amount the initial asset ratio (initToken0Amount:initToken1Amount)
/// @param initToken1Amount the initial asset ratio (initToken0Amount:initToken1Amount)
/// @return pair the address of new token pair
function createPair(
address token,
uint256 initToken0Amount,
uint256 initToken1Amount
)
external
returns (address pair);
function getPair(address token) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function getTradeMiningStatus(address token) external view returns (bool status);
function setTradeMiningStatus(address token, bool status) external;
function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs
function setFeeVaultForLP(address token, address feeVault) external;
function setGovernance(address _new) external;
function setController(address _new) external;
function setFeeReceiver(address _new) external;
function setVaultForLP(address _new) external;
function setVaultForTrader(address _new) external;
function setVaultForCNode(address _new) external;
function setDAO(address _new) external;
function getController() external view returns (address controller);
function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders
function getVaultForLP() external view returns (address vaultForLP);
function getVaultForTrader() external view returns (address vaultForTrader);
function getVaultForCNode() external view returns (address vaultForCNode);
function getDAO() external view returns (address dao);
}
// File: contracts/CoFiXV2Factory.sol
pragma solidity 0.6.12;
// Factory of CoFiX to create new CoFiXPair contract when new pair is created, managed by governance
// Governance role of this contract should be the `Timelock` contract, which is further managed by a multisig contract
contract CoFiXV2Factory is ICoFiXV2Factory {
string constant internal pairNamePrefix = "XToken ";
string constant internal pairSymbolPrefix = "XT-";
mapping(address => address) public override getPair;
address[] public override allPairs;
address public immutable WETH;
address public governance;
address public controller;
address public feeReceiver;
address public vaultForLP;
address public vaultForTrader;
address public vaultForCNode;
address public dao;
mapping (address => bool) public override getTradeMiningStatus; // token -> bool
mapping (address => address) public override getFeeVaultForLP; // token -> fee vault pool
modifier onlyGovernance() {
require(msg.sender == governance, "CFactory: !governance");
_;
}
constructor(address _WETH) public {
governance = msg.sender;
feeReceiver = msg.sender; // set feeReceiver to a feeReceiver contract later
WETH = _WETH;
}
function allPairsLength() external override view returns (uint256) {
return allPairs.length;
}
function pairCodeHash() external pure returns (bytes32) {
return keccak256(type(CoFiXV2Pair).creationCode);
}
function createPair(address token, uint256 initToken0Amount, uint256 initToken1Amount) external override onlyGovernance returns (address pair) {
require(token != address(0), 'CFactory: ZERO_ADDRESS');
require(getPair[token] == address(0), 'CFactory: PAIR_EXISTS');
require(initToken0Amount > 0 && initToken1Amount > 0, "CFactory: ILLEGAL_AMOUNT");
bytes memory bytecode = type(CoFiXV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(pair != address(0), "CFactory: Failed on deploy");
getPair[token] = pair;
allPairs.push(pair);
uint256 pairLen = allPairs.length;
string memory _idx = uint2str(pairLen);
string memory _name = append(pairNamePrefix, _idx);
string memory _symbol = append(pairSymbolPrefix, _idx);
ICoFiXV2Pair(pair).initialize(WETH, token, _name, _symbol, initToken0Amount, initToken1Amount);
ICoFiXV2Controller(controller).addCaller(pair);
emit PairCreated(token, pair, pairLen);
}
function setGovernance(address _new) external override onlyGovernance {
require(_new != address(0), "CFactory: zero addr");
require(_new != governance, "CFactory: same addr");
governance = _new;
emit NewGovernance(_new);
}
function setController(address _new) external override onlyGovernance {
require(_new != address(0), "CFactory: zero addr");
require(_new != controller, "CFactory: same addr");
controller = _new;
emit NewController(_new);
}
function setFeeReceiver(address _new) external override onlyGovernance {
require(_new != address(0), "CFactory: zero addr");
require(_new != feeReceiver, "CFactory: same addr");
feeReceiver = _new;
emit NewFeeReceiver(_new);
}
function setFeeVaultForLP(address token, address feeVault) external override onlyGovernance {
getFeeVaultForLP[token] = feeVault;
emit NewFeeVaultForLP(token, feeVault);
}
function setVaultForLP(address _new) external override onlyGovernance {
require(_new != address(0), "CFactory: zero addr");
require(_new != vaultForLP, "CFactory: same addr");
vaultForLP = _new;
emit NewVaultForLP(_new);
}
function setVaultForTrader(address _new) external override onlyGovernance {
require(_new != address(0), "CFactory: zero addr");
require(_new != vaultForTrader, "CFactory: same addr");
vaultForTrader = _new;
emit NewVaultForTrader(_new);
}
function setVaultForCNode(address _new) external override onlyGovernance {
require(_new != address(0), "CFactory: zero addr");
require(_new != vaultForCNode, "CFactory: same addr");
vaultForCNode = _new;
emit NewVaultForCNode(_new);
}
function setDAO(address _new) external override onlyGovernance {
require(_new != address(0), "CFactory: zero addr");
require(_new != dao, "CFactory: same addr");
dao = _new;
emit NewDAO(_new);
}
function setTradeMiningStatus(address token, bool status) external override onlyGovernance {
getTradeMiningStatus[token] = status;
}
function getController() external view override returns (address) {
return controller;
}
function getFeeReceiver() external view override returns (address) {
return feeReceiver;
}
function getVaultForLP() external view override returns (address) {
return vaultForLP;
}
function getVaultForTrader() external view override returns (address) {
return vaultForTrader;
}
function getVaultForCNode() external view override returns (address) {
return vaultForCNode;
}
function getDAO() external view override returns (address) {
return dao;
}
// internal helpers
function append(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
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 - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
} | get Net Asset Value Per Share for burn only for read, could cost more gas if use it directly in contract | function getNAVPerShareForBurn(OraclePrice memory _op) external view returns (uint256 navps) {
return calcNAVPerShare(reserve0, reserve1, _op.ethAmount, _op.erc20Amount);
}
| 10,545,523 |
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @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;
}
}
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);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
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);
}
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
pragma solidity ^0.6.12;
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;
}
}
contract Whitelist is Ownable {
// Mapping of address to boolean indicating whether the address is whitelisted
mapping(address => bool) private whitelistMap;
// flag controlling whether whitelist is enabled.
bool private whitelistEnabled = true;
event AddToWhitelist(address indexed _newAddress);
event RemoveFromWhitelist(address indexed _removedAddress);
/**
* @dev Enable or disable the whitelist
* @param _enabled bool of whether to enable the whitelist.
*/
function enableWhitelist(bool _enabled) public onlyOwner {
whitelistEnabled = _enabled;
}
/**
* @dev Adds the provided address to the whitelist
* @param _newAddress address to be added to the whitelist
*/
function addToWhitelist(address _newAddress) public onlyOwner {
_whitelist(_newAddress);
emit AddToWhitelist(_newAddress);
}
/**
* @dev Removes the provided address to the whitelist
* @param _removedAddress address to be removed from the whitelist
*/
function removeFromWhitelist(address _removedAddress) public onlyOwner {
_unWhitelist(_removedAddress);
emit RemoveFromWhitelist(_removedAddress);
}
/**
* @dev Returns whether the address is whitelisted
* @param _address address to check
* @return bool
*/
function isWhitelisted(address _address) public view returns (bool) {
if (whitelistEnabled) {
return whitelistMap[_address];
} else {
return true;
}
}
/**
* @dev Internal function for removing an address from the whitelist
* @param _removedAddress address to unwhitelisted
*/
function _unWhitelist(address _removedAddress) internal {
whitelistMap[_removedAddress] = false;
}
/**
* @dev Internal function for adding the provided address to the whitelist
* @param _newAddress address to be added to the whitelist
*/
function _whitelist(address _newAddress) internal {
whitelistMap[_newAddress] = true;
}
}
contract Aart is ERC721 ,Whitelist{
// Optional mapping for token URIs
using SafeMath for uint256;
uint256 private numbers;
constructor() public ERC721("AART NFT","AART") {
}
/**
* @dev Checks that the token is owned by the sender.
* @param _tokenId uint256 ID of the token.
*/
modifier onlyTokenOwner(uint256 _tokenId) {
address owner = ownerOf(_tokenId);
require(owner == msg.sender, "must be the owner of the token");
_;
}
/**
* @dev Whitelists a bunch of addresses.
* @param _whitelistees address[] of addresses to whitelist.
*/
function addWhitelist(address[] memory _whitelistees) public onlyOwner {
// Add all whitelistees.
for (uint256 i = 0; i < _whitelistees.length; i++) {
address creator = _whitelistees[i];
if (!isWhitelisted(creator)) {
_whitelist(creator);
}
}
}
function mint(address _account,string memory _tokenURI) public {
require(isWhitelisted(msg.sender), "must be whitelisted to create tokens");
numbers++;
uint256 newId = numbers;
_safeMint( _account, newId);
_setTokenURI(newId,_tokenURI);
}
function setbaseuri(string memory _baseuri) public onlyOwner {
_setBaseURI(_baseuri);
}
/**
* @dev Deletes the token with the provided ID.
* @param _tokenId uint256 ID of the token.
*/
function deleteToken(uint256 _tokenId) public onlyTokenOwner(_tokenId) {
_burn(_tokenId);
}
} | Whitelists a bunch of addresses. _whitelistees address[] of addresses to whitelist./ Add all whitelistees. | function addWhitelist(address[] memory _whitelistees) public onlyOwner {
for (uint256 i = 0; i < _whitelistees.length; i++) {
address creator = _whitelistees[i];
if (!isWhitelisted(creator)) {
_whitelist(creator);
}
}
}
| 14,655,351 |
./full_match/1/0xB6BeBe5000B70CAb62137566f108356521E1f05B/sources/PawfectClub.sol | Update the presale mint price/ | function setPresalePrice(uint256 _presalePrice) external onlyOwner {
presalePrice = _presalePrice;
}
| 2,905,478 |
./full_match/11155111/0xbdDB47066f93690e6de26037646ECe6D1F468245/sources/staking/saturn_staking.sol | This function is used to get the total no of tokens that are staked/ | function getTotalStakedTokens() external view returns (uint256) {
return _totalStakedTokens;
}
| 3,834,582 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/[email protected]/token/ERC20/IERC20.sol";
import "@openzeppelin/[email protected]/token/ERC20/SafeERC20.sol";
import "@openzeppelin/[email protected]/math/SafeMath.sol";
import "@openzeppelin/[email protected]/access/Ownable.sol";
import "./Meshcoin.sol";
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once Meshcoin is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MeshcoinPools is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardRemain; // Remain rewards
// We do some fancy math here. Basically, any point in time, the amount of Meshcoins
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accRewardPerShare) + user.rewardRemain - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated.
// 2. User calc the pending rewards and record at rewardRemain.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. Meshcoins to distribute per block.
uint256 lastRewardBlock; // Last block number that Meshcoins distribution occurs.
uint256 accRewardPerShare; // Accumulated Meshcoins per share, times 1e18. See below.
uint256 totalAmount; // Total amount of current pool deposit.
uint256 pooltype; // pool type, 1 = Single ERC20 or 2 = LP Token or 3 = nft Pool
}
// The Meshcoin!
Meshcoin public msc;
// Dev address.
address public devaddr;
// Operater address.
address public opeaddr;
// Meshcoins created per block.
uint256 public rewardPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// the Meshcoins distribution
uint256 public rewardDistributionFactor = 1e9;
// The block number when Meshcoin mining starts.
uint256 public startBlock;
// Reduction
uint256 public reductionBlockPeriod; // 60/3*60*24*7 = 201600
uint256 public maxReductionCount;
uint256 public nextReductionBlock;
uint256 public reductionCounter;
// Block number when bonus MSC reduction period ends.
uint256 public bonusStableBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Claim(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor (
Meshcoin _msc,
address _devaddr,
address _opeaddr,
uint256 _rewardPerBlock,
uint256 _startBlock
) public {
require(_devaddr != address(0), "_devaddr address cannot be 0");
require(_opeaddr != address(0), "_opeaddr address cannot be 0");
msc = _msc;
devaddr = _devaddr;
opeaddr = _opeaddr;
startBlock = _startBlock;
rewardPerBlock = _rewardPerBlock;
reductionBlockPeriod = 201600; // 60/3*60*24*7 = 201600
maxReductionCount = 12;
bonusStableBlock = _startBlock.add(reductionBlockPeriod.mul(maxReductionCount));
nextReductionBlock = _startBlock.add(reductionBlockPeriod);
}
modifier validatePoolByPid(uint256 _pid) {
require (_pid < poolInfo.length , "Pool does not exist") ;
_;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _pooltype) external onlyOwner {
uint256 _len = poolInfo.length;
for(uint256 i = 0; i < _len; i++){
require(_lpToken != poolInfo[i].lpToken, "LPToken already exists");
}
massUpdatePools();
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRewardPerShare: 0,
totalAmount: 0,
pooltype: _pooltype
}));
}
// Set the number of msc produced by each block
function setRewardPerBlock(uint256 _newPerBlock) external onlyOwner {
massUpdatePools();
rewardPerBlock = _newPerBlock;
}
function setRewardDistributionFactor(uint256 _rewardDistributionFactor) external onlyOwner {
massUpdatePools();
rewardDistributionFactor = _rewardDistributionFactor;
}
// Update the given pool's Meshcoin allocation point. Can only be called by the owner.
function setAllocPoint(uint256 _pid, uint256 _allocPoint) external onlyOwner validatePoolByPid(_pid) {
massUpdatePools();
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Pooltype to set pool display type on frontend.
function setPoolType(uint256 _pid, uint256 _pooltype) external onlyOwner validatePoolByPid(_pid) {
poolInfo[_pid].pooltype = _pooltype;
}
function setReductionArgs(uint256 _reductionBlockPeriod, uint256 _maxReductionCount) external onlyOwner {
nextReductionBlock = nextReductionBlock.sub(reductionBlockPeriod).add(_reductionBlockPeriod);
bonusStableBlock = nextReductionBlock.add(_reductionBlockPeriod.mul(_maxReductionCount.sub(reductionCounter).sub(1)));
reductionBlockPeriod = _reductionBlockPeriod;
maxReductionCount = _maxReductionCount;
}
// Return reward multiplier over the given _from to _to block.
function getBlocksReward(uint256 _from, uint256 _to) public view returns (uint256 value) {
uint256 prevReductionBlock = nextReductionBlock.sub(reductionBlockPeriod);
if ((_from >= prevReductionBlock && _to <= nextReductionBlock) ||
(_from > bonusStableBlock))
{
value = getBlockReward(_to.sub(_from), rewardPerBlock, reductionCounter);
}
else if (_from < prevReductionBlock && _to < nextReductionBlock)
{
uint256 part1 = getBlockReward(_to.sub(prevReductionBlock), rewardPerBlock, reductionCounter);
uint256 part2 = getBlockReward(prevReductionBlock.sub(_from), rewardPerBlock, reductionCounter.sub(1));
value = part1.add(part2);
}
else // if (_from > prevReductionBlock && _to > nextReductionBlock)
{
uint256 part1 = getBlockReward(_to.sub(nextReductionBlock), rewardPerBlock, reductionCounter.add(1));
uint256 part2 = getBlockReward(nextReductionBlock.sub(_from), rewardPerBlock, reductionCounter);
value = part1.add(part2);
}
value = value.mul(rewardDistributionFactor).div(1e9);
}
// Return reward per block
function getBlockReward(uint256 _blockCount, uint256 _rewardPerBlock, uint256 _reductionCounter) internal view returns (uint256) {
uint256 reward = _blockCount.mul(_rewardPerBlock);
if (_reductionCounter == 0) {
return reward;
}else if (_reductionCounter >= maxReductionCount) {
return reward.mul(75).div(1000);
}
// _reductionCounter no more than maxReductionCount (12)
return reward.mul(80 ** _reductionCounter).div(100 ** _reductionCounter);
}
// View function to see pending Meshcoins on frontend.
function pendingRewards(uint256 _pid, address _user) public validatePoolByPid(_pid) view returns (uint256 value) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
value = totalRewards(pool, user).add(user.rewardRemain).sub(user.rewardDebt);
}
function totalRewards(PoolInfo memory _pool, UserInfo memory _user) internal view returns (uint256 value) {
uint256 accRewardPerShare = _pool.accRewardPerShare;
if (block.number > _pool.lastRewardBlock && _pool.totalAmount != 0) {
uint256 blockReward = getBlocksReward(_pool.lastRewardBlock, block.number);
uint256 poolReward = blockReward.mul(_pool.allocPoint).div(totalAllocPoint);
accRewardPerShare = accRewardPerShare.add(poolReward.mul(1e18).div(_pool.totalAmount));
}
value = _user.amount.mul(accRewardPerShare).div(1e18);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public validatePoolByPid(_pid) {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.allocPoint == 0) {
return;
}
if (block.number > nextReductionBlock) {
if(reductionCounter >= maxReductionCount) {
bonusStableBlock = nextReductionBlock;
}else{
nextReductionBlock = nextReductionBlock.add(reductionBlockPeriod);
reductionCounter = reductionCounter.add(1);
}
}
if (pool.totalAmount == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 blockReward = getBlocksReward(pool.lastRewardBlock, block.number);
uint256 poolReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint);
if(poolReward > 0) {
// 1998%% for pools, 500%% for team and 200%% for business
msc.liquidityMiningMint(devaddr, poolReward.mul(500).div(1998));
msc.liquidityMiningMint(opeaddr, poolReward.mul(200).div(1998));
msc.liquidityMiningMint(address(this), poolReward);
}
pool.accRewardPerShare = pool.accRewardPerShare.add(poolReward.mul(1e18).div(pool.totalAmount));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for Meshcoin allocation.
function deposit(uint256 _pid, uint256 _amount) external validatePoolByPid(_pid) {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
user.rewardRemain = pendingRewards(_pid, msg.sender);
// user.rewardDebt = 0;
}
if(_amount > 0) {
user.amount = user.amount.add(_amount);
pool.totalAmount = pool.totalAmount.add(_amount);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
user.rewardDebt = totalRewards(pool, user);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MeshcoinPool.
function withdraw(uint256 _pid, uint256 _amount) external validatePoolByPid(_pid){
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
user.rewardRemain = pendingRewards(_pid, msg.sender);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.totalAmount = pool.totalAmount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = totalRewards(pool, user);
emit Withdraw(msg.sender, _pid, _amount);
}
function claimAll(uint256 _pid) external validatePoolByPid(_pid) returns(uint256 value){
updatePool(_pid);
value = pendingRewards(_pid, msg.sender);
// require(value >= 0, "claim: not good");
if (value > 0) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
user.rewardRemain = 0;
user.rewardDebt = totalRewards(pool, user);
safeMscTransfer(msg.sender, value);
}
emit Claim(msg.sender, _pid, value);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) external validatePoolByPid(_pid){
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.rewardRemain = 0;
pool.totalAmount = pool.totalAmount.sub(amount);
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe Meshcoin transfer function, just in case if rounding error causes pool to not have enough Meshcoins.
function safeMscTransfer(address _to, uint256 _amount) internal {
uint256 mscBalance = msc.balanceOf(address(this));
if (_amount > mscBalance) {
msc.transfer(_to, mscBalance);
} else {
msc.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) external {
require(_devaddr != address(0), "_devaddr address cannot be 0");
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
// Update ope address by the previous ope.
function ope(address _opeaddr) external {
require(_opeaddr != address(0), "_devaddr address cannot be 0");
require(msg.sender == opeaddr, "ope: wut?");
opeaddr = _opeaddr;
}
// If the user transfers TH to contract, it will revert
receive() external payable {
revert();
}
}
| Return reward multiplier over the given _from to _to block. | function getBlocksReward(uint256 _from, uint256 _to) public view returns (uint256 value) {
uint256 prevReductionBlock = nextReductionBlock.sub(reductionBlockPeriod);
if ((_from >= prevReductionBlock && _to <= nextReductionBlock) ||
(_from > bonusStableBlock))
{
value = getBlockReward(_to.sub(_from), rewardPerBlock, reductionCounter);
}
else if (_from < prevReductionBlock && _to < nextReductionBlock)
{
uint256 part1 = getBlockReward(_to.sub(prevReductionBlock), rewardPerBlock, reductionCounter);
uint256 part2 = getBlockReward(prevReductionBlock.sub(_from), rewardPerBlock, reductionCounter.sub(1));
value = part1.add(part2);
}
{
uint256 part1 = getBlockReward(_to.sub(nextReductionBlock), rewardPerBlock, reductionCounter.add(1));
uint256 part2 = getBlockReward(nextReductionBlock.sub(_from), rewardPerBlock, reductionCounter);
value = part1.add(part2);
}
value = value.mul(rewardDistributionFactor).div(1e9);
}
| 13,112,096 |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../utility/ContractRegistryClient.sol";
import "../token/ReserveToken.sol";
import "./interfaces/IConverter.sol";
import "./interfaces/IConverterUpgrader.sol";
import "./interfaces/IConverterFactory.sol";
interface ILegacyConverterVersion45 is IConverter {
function withdrawTokens(
IReserveToken token,
address recipient,
uint256 amount
) external;
function withdrawETH(address payable recipient) external;
}
/**
* @dev This contract contract allows upgrading an older converter contract (0.4 and up)
* to the latest version.
* To begin the upgrade process, simply execute the 'upgrade' function.
* At the end of the process, the ownership of the newly upgraded converter will be transferred
* back to the original owner and the original owner will need to execute the 'acceptOwnership' function.
*
* the address of the new converter is available in the ConverterUpgrade event.
*
* note that for older converters that don't yet have the 'upgrade' function, ownership should first
* be transferred manually to the ConverterUpgrader contract using the 'transferOwnership' function
* and then the upgrader 'upgrade' function should be executed directly.
*/
contract ConverterUpgrader is IConverterUpgrader, ContractRegistryClient {
using ReserveToken for IReserveToken;
/**
* @dev triggered when the contract accept a converter ownership
*/
event ConverterOwned(IConverter indexed converter, address indexed owner);
/**
* @dev triggered when the upgrading process is done
*/
event ConverterUpgrade(address indexed oldConverter, address indexed newConverter);
/**
* @dev initializes a new ConverterUpgrader instance
*/
constructor(IContractRegistry registry) public ContractRegistryClient(registry) {}
/**
* @dev upgrades an old converter to the latest version
*
* Requirements:
*
* - the caller must be the converter itself
* - the converter must transfer the ownership to the upgrader before calling this function
*/
function upgrade(bytes32 version) external override {
upgradeOld(IConverter(msg.sender), version);
}
/**
* @dev upgrades an old converter to the latest version
*
* Requirements:
*
* - the caller must be the converter itself
* - the converter must transfer the ownership to the upgrader before calling this function
*/
function upgrade(uint16 version) external override {
_upgrade(IConverter(msg.sender), version);
}
/**
* @dev upgrades an old converter to the latest version
*
* Requirements:
*
* - the caller must be the converter itself
* - the converter must transfer the ownership to the upgrader before calling this function
*/
function upgradeOld(
IConverter converter,
bytes32 /* version */
) public {
// the upgrader doesn't require the version for older converters
_upgrade(converter, 0);
}
/**
* @dev upgrades an old converter to the latest version
*
* Requirements:
*
* - the caller must be the converter itself
* - the converter must transfer the ownership to the upgrader before calling this function
*/
function _upgrade(IConverter converter, uint16 version) private {
address prevOwner = converter.owner();
_acceptConverterOwnership(converter);
IConverter newConverter = _createConverter(converter);
_copyReserves(converter, newConverter);
_copyConversionFee(converter, newConverter);
_transferReserveBalances(converter, newConverter, version);
IConverterAnchor anchor = converter.token();
if (anchor.owner() == address(converter)) {
converter.transferTokenOwnership(address(newConverter));
newConverter.acceptAnchorOwnership();
}
converter.transferOwnership(prevOwner);
newConverter.transferOwnership(prevOwner);
newConverter.onUpgradeComplete();
emit ConverterUpgrade(address(converter), address(newConverter));
}
/**
* @dev the first step when upgrading a converter is to transfer the ownership to the local contract
*
* Requirements:
*
* - the upgrader contract then needs to accept the ownership transfer before initiating the upgrade process
* - the converter must transfer the ownership to the upgrader before calling this function
*/
function _acceptConverterOwnership(IConverter oldConverter) private {
oldConverter.acceptOwnership();
emit ConverterOwned(oldConverter, address(this));
}
/**
* @dev creates a new converter with same basic data as the original old converter
*/
function _createConverter(IConverter oldConverter) private returns (IConverter) {
IConverterAnchor anchor = oldConverter.token();
uint32 maxConversionFee = oldConverter.maxConversionFee();
uint16 reserveTokenCount = oldConverter.connectorTokenCount();
// determine new converter type
uint16 newType = 0;
// new converter - get the type from the converter itself
if (_isV28OrHigherConverter(oldConverter)) {
newType = oldConverter.converterType();
} else {
assert(reserveTokenCount > 1);
newType = 1;
}
if (newType == 1 && reserveTokenCount == 2) {
(, uint32 weight0, , , ) = oldConverter.connectors(oldConverter.connectorTokens(0));
(, uint32 weight1, , , ) = oldConverter.connectors(oldConverter.connectorTokens(1));
if (weight0 == PPM_RESOLUTION / 2 && weight1 == PPM_RESOLUTION / 2) {
newType = 3;
}
}
IConverterFactory converterFactory = IConverterFactory(_addressOf(CONVERTER_FACTORY));
IConverter converter = converterFactory.createConverter(newType, anchor, registry(), maxConversionFee);
converter.acceptOwnership();
return converter;
}
/**
* @dev copies the reserves from the old converter to the new one
*
* note that this will not work for an unlimited number of reserves due to block gas limit constraints
*/
function _copyReserves(IConverter oldConverter, IConverter newConverter) private {
uint16 reserveTokenCount = oldConverter.connectorTokenCount();
for (uint16 i = 0; i < reserveTokenCount; i++) {
IReserveToken reserveAddress = oldConverter.connectorTokens(i);
(, uint32 weight, , , ) = oldConverter.connectors(reserveAddress);
newConverter.addReserve(reserveAddress, weight);
}
}
/**
* @dev copies the conversion fee from the old converter to the new one
*/
function _copyConversionFee(IConverter oldConverter, IConverter newConverter) private {
uint32 conversionFee = oldConverter.conversionFee();
newConverter.setConversionFee(conversionFee);
}
/**
* @dev transfers the balance of each reserve in the old converter to the new one
*
* note that the function assumes that the new converter already has the exact same number of reserves
* also, this will not work for an unlimited number of reserves due to block gas limit constraints
*/
function _transferReserveBalances(
IConverter oldConverter,
IConverter newConverter,
uint16 version
) private {
if (version <= 45) {
_transferReserveBalancesVersion45(ILegacyConverterVersion45(address(oldConverter)), newConverter);
return;
}
oldConverter.transferReservesOnUpgrade(address(newConverter));
}
/**
* @dev transfers the balance of each reserve in the old converter to the new one
*
* note that the function assumes that the new converter already has the exact same number of reserves
* also, this will not work for an unlimited number of reserves due to block gas limit constraints
*/
function _transferReserveBalancesVersion45(ILegacyConverterVersion45 oldConverter, IConverter newConverter)
private
{
uint16 reserveTokenCount = oldConverter.connectorTokenCount();
for (uint16 i = 0; i < reserveTokenCount; i++) {
IReserveToken reserveToken = oldConverter.connectorTokens(i);
uint256 reserveBalance = reserveToken.balanceOf(address(oldConverter));
if (reserveBalance > 0) {
if (reserveToken.isNativeToken()) {
oldConverter.withdrawETH(address(newConverter));
} else {
oldConverter.withdrawTokens(reserveToken, address(newConverter), reserveBalance);
}
}
}
}
bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()"));
/**
* @dev we're using a static call to identify converter version
*
* note that we can't rely on the version number since the function had a different signature in older converters
*/
function _isV28OrHigherConverter(IConverter converter) internal view returns (bool) {
bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR);
(bool success, bytes memory returnData) = address(converter).staticcall{ gas: 4000 }(data);
if (success && returnData.length == 32) {
return abi.decode(returnData, (bool));
}
return false;
}
}
| we're using a static call to identify converter version note that we can't rely on the version number since the function had a different signature in older converters/ | function _isV28OrHigherConverter(IConverter converter) internal view returns (bool) {
bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR);
if (success && returnData.length == 32) {
return abi.decode(returnData, (bool));
}
return false;
}
| 12,938,655 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
// Part: IPriceFeed
interface IPriceFeed {
function initialize(
uint256 maxSafePriceDifference,
address stableSwapOracleAddress,
address curvePoolAddress,
address admin
) 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: StorageSlot
/**
* @dev Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/StorageSlot.sol
*/
library StorageSlot {
struct AddressSlot {
address value;
}
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
}
// Part: OpenZeppelin/[email protected]/Proxy
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// Part: OpenZeppelin/[email protected]/ERC1967Proxy
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
Address.functionDelegateCall(_logic, _data);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967Proxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// File: PriceFeedProxy.sol
contract PriceFeedProxy is ERC1967Proxy {
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Initializes the upgradeable proxy with an initial implementation
* specified by `priceFeedImpl`, calling its `initialize` function
* on the proxy contract state.
*/
constructor(
address priceFeedImpl,
uint256 maxSafePriceDifference,
address stableSwapOracleAddress,
address curvePoolAddress,
address admin
)
payable
ERC1967Proxy(
priceFeedImpl,
abi.encodeWithSelector(
IPriceFeed(address(0)).initialize.selector,
maxSafePriceDifference,
stableSwapOracleAddress,
curvePoolAddress,
admin
)
)
{
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(admin);
}
/**
* @dev Returns the current implementation address.
*/
function implementation() external view returns (address) {
return _implementation();
}
/**
* @dev Upgrades the proxy to a new implementation, optionally performing an additional setup call.
*
* Emits an {Upgraded} event.
*
* @param setupCalldata Data for the setup call. The call is skipped if data is empty.
*/
function upgradeTo(address newImplementation, bytes memory setupCalldata) external {
require(msg.sender == _getAdmin(), "ERC1967: unauthorized");
_upgradeTo(newImplementation);
if (setupCalldata.length > 0) {
Address.functionDelegateCall(newImplementation, setupCalldata, "ERC1967: setup failed");
}
}
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Returns the current admin of the proxy.
*/
function getProxyAdmin() external view returns (address) {
return _getAdmin();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function changeProxyAdmin(address newAdmin) external {
address admin = _getAdmin();
require(msg.sender == admin, "ERC1967: unauthorized");
emit AdminChanged(admin, newAdmin);
_setAdmin(newAdmin);
}
} | Returns the current admin of the proxy./ | function getProxyAdmin() external view returns (address) {
return _getAdmin();
}
| 89,264 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorSettings.sol)
pragma solidity ^0.8.0;
import "../Governor.sol";
import "../../utils/Timers.sol";
/**
* @dev Extension of {Governor} for settings updatable through governance.
*
* _Available since v4.4._
*/
abstract contract GovernorSettings is Governor {
uint256 private _contestStart;
uint256 private _votingDelay;
uint256 private _votingPeriod;
uint256 private _contestSnapshot;
uint256 private _proposalThreshold;
uint256 private _numAllowedProposalSubmissions;
uint256 private _maxProposalCount;
address private _creator;
event ContestStartSet(uint256 oldContestStart, uint256 newContestStart);
event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay);
event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod);
event ContestSnapshotSet(uint256 oldContestSnapshot, uint256 newContestSnapshot);
event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold);
event NumAllowedProposalSubmissionsSet(uint256 oldNumAllowedProposalSubmissions, uint256 newNumAllowedProposalSubmissions);
event MaxProposalCountSet(uint256 oldMaxProposalCount, uint256 newMaxProposalCount);
event CreatorSet(address oldCreator, address newCreator);
/**
* @dev Initialize the governance parameters.
*/
constructor(
uint256 initialContestStart,
uint256 initialVotingDelay,
uint256 initialVotingPeriod,
uint256 initialContestSnapshot,
uint256 initialProposalThreshold,
uint256 initialNumAllowedProposalSubmissions,
uint256 initialMaxProposalCount
) {
_setContestStart(initialContestStart);
_setVotingDelay(initialVotingDelay);
_setVotingPeriod(initialVotingPeriod);
_setContestSnapshot(initialContestSnapshot);
_setProposalThreshold(initialProposalThreshold);
_setNumAllowedProposalSubmissions(initialNumAllowedProposalSubmissions);
_setMaxProposalCount(initialMaxProposalCount);
_setCreator(msg.sender);
}
/**
* @dev See {IGovernor-contestStart}.
*/
function contestStart() public view virtual override returns (uint256) {
return _contestStart;
}
/**
* @dev See {IGovernor-votingDelay}.
*/
function votingDelay() public view virtual override returns (uint256) {
return _votingDelay;
}
/**
* @dev See {IGovernor-votingPeriod}.
*/
function votingPeriod() public view virtual override returns (uint256) {
return _votingPeriod;
}
/**
* @dev See {IGovernor-contestSnapshot}.
*/
function contestSnapshot() public view virtual override returns (uint256) {
return _contestSnapshot;
}
/**
* @dev See {Governor-proposalThreshold}.
*/
function proposalThreshold() public view virtual override returns (uint256) {
return _proposalThreshold;
}
/**
* @dev See {Governor-numAllowedProposalSubmissions}.
*/
function numAllowedProposalSubmissions() public view virtual override returns (uint256) {
return _numAllowedProposalSubmissions;
}
/**
* @dev Max number of proposals allowed in this contest
*/
function maxProposalCount() public view virtual override returns (uint256) {
return _maxProposalCount;
}
/**
* @dev See {IGovernor-creator}.
*/
function creator() public view virtual override returns (address) {
return _creator;
}
/**
* @dev Internal setter for the contestStart.
*
* Emits a {ContestStartSet} event.
*/
function _setContestStart(uint256 newContestStart) internal virtual {
emit ContestStartSet(_contestStart, newContestStart);
_contestStart = newContestStart;
}
/**
* @dev Internal setter for the voting delay.
*
* Emits a {VotingDelaySet} event.
*/
function _setVotingDelay(uint256 newVotingDelay) internal virtual {
emit VotingDelaySet(_votingDelay, newVotingDelay);
_votingDelay = newVotingDelay;
}
/**
* @dev Internal setter for the voting period.
*
* Emits a {VotingPeriodSet} event.
*/
function _setVotingPeriod(uint256 newVotingPeriod) internal virtual {
// voting period must be at least one block long
require(newVotingPeriod > 0, "GovernorSettings: voting period too low");
emit VotingPeriodSet(_votingPeriod, newVotingPeriod);
_votingPeriod = newVotingPeriod;
}
/**
* @dev Internal setter for the contestStart.
*
* Emits a {ContestSnapshotSet} event.
*/
function _setContestSnapshot(uint256 newContestSnapshot) internal virtual {
emit ContestSnapshotSet(_contestSnapshot, newContestSnapshot);
_contestSnapshot = newContestSnapshot;
}
/**
* @dev Internal setter for the proposal threshold.
*
* Emits a {ProposalThresholdSet} event.
*/
function _setProposalThreshold(uint256 newProposalThreshold) internal virtual {
emit ProposalThresholdSet(_proposalThreshold, newProposalThreshold);
_proposalThreshold = newProposalThreshold;
}
/**
* @dev Internal setter for the number of allowed proposal submissions per permissioned address.
*
* Emits a {NumAllowedProposalSubmissionsSet} event.
*/
function _setNumAllowedProposalSubmissions(uint256 newNumAllowedProposalSubmissions) internal virtual {
emit NumAllowedProposalSubmissionsSet(_numAllowedProposalSubmissions, newNumAllowedProposalSubmissions);
_numAllowedProposalSubmissions = newNumAllowedProposalSubmissions;
}
/**
* @dev Internal setter for the max proposal count.
*
* Emits a {MaxProposalCountSet} event.
*/
function _setMaxProposalCount(uint256 newMaxProposalCount) internal virtual {
emit MaxProposalCountSet(_maxProposalCount, newMaxProposalCount);
_maxProposalCount = newMaxProposalCount;
}
/**
* @dev Internal setter for creator.
*
* Emits a {CreatorSet} event.
*/
function _setCreator(address newCreator) internal virtual {
emit CreatorSet(_creator, newCreator);
_creator = newCreator;
}
}
| Internal setter for creator. Emits a {CreatorSet} event./ | function _setCreator(address newCreator) internal virtual {
emit CreatorSet(_creator, newCreator);
_creator = newCreator;
}
| 7,297,544 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract AutoCompoundFarm is ReentrancyGuard, Pausable, Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
struct UserInfo {
uint amount;
uint divisor;
uint pastPending;
}
IERC20 public immutable krw;
bool public multiplierIsMaxed;
uint public dailyBlocks;
uint public totalStaked;
uint public totalPending;
uint public multiplier;
uint16 public fee;
uint public targetDailyCompoundRate;
uint public maxRewardsPerBlock;
uint public rewardsPerBlock;
uint public lastRewardBlock;
uint public finalBlock;
address public vault;
mapping(address => UserInfo) public stakes;
event Deposit(address indexed user, uint amount);
event Withdraw(address indexed user, uint amount);
event Claim(address indexed user, uint amount);
event EmergencyWithdraw(address indexed user, uint amount);
/**
* @dev initialise the autocompounding farm. Fee defaults to zero
* @param _krw contract address for krown
* @param _vault address to send fees to
* @param _maxRewardsPerBlock the maximum amount of krown rewards to be distributed per block
* @param _targetDailyCompoundRate the daily compounding rate used to determine the amount of krown rewards per block
*/
constructor(
address _krw,
address _vault,
uint _maxRewardsPerBlock,
uint _targetDailyCompoundRate
) {
krw = IERC20(_krw);
multiplierIsMaxed = false;
dailyBlocks = 1e18 * 20 * 60 * 24; // Based on 3 second per block on BSC
totalStaked = 0;
totalPending = 0;
multiplier = 1e18;
fee = 0;
targetDailyCompoundRate = _targetDailyCompoundRate;
maxRewardsPerBlock = _maxRewardsPerBlock;
rewardsPerBlock = 0;
lastRewardBlock = block.number;
finalBlock = type(uint).max;
vault = _vault;
}
/// @dev retrieves the amount deposited by the user
function getDeposit(address account) external view returns(uint) {
return stakes[account].amount;
}
/// @dev calculates and returns the APY
function getAPY() external view returns(uint) {
return totalStaked == 0 ? 0 : (rewardsPerBlock * dailyBlocks * 365) / (totalStaked + totalPending);
}
/// @dev updates the daily blocks variable
/// @param _dailyBlocks the expected number of blocks to be mined per day
function changeDailyBlocks(uint _dailyBlocks) external onlyOwner {
dailyBlocks = _dailyBlocks;
}
/// @dev updates the final block variable
/// @param _finalBlock the block number after which reward distribution will halt
function changeFinalBlock(uint _finalBlock) external onlyOwner {
finalBlock = _finalBlock;
}
/// @dev updates the fee variable
/// @param _fee the % fee for depositing e.g. 100 = 1%
function changeFee(uint16 _fee) public onlyOwner {
require(_fee <= 10000, "Invalid fee");
fee = _fee;
}
/// @dev updates the maximum rewards per block variable
/// @param _maxRewardsPerBlock the maximum amount of the token to be distributed per block
function changeMaxRewardsPerBlock(uint _maxRewardsPerBlock) external onlyOwner {
maxRewardsPerBlock = _maxRewardsPerBlock;
}
/// @dev updates the daily compound rate target variable
/// @param _targetDailyCompoundRate the daily compounding rate used to determine the amount of krown rewards per block
function changeTargetDailyCompoundRate(uint _targetDailyCompoundRate) external onlyOwner {
require(_targetDailyCompoundRate > 1e18, "Target compound rate must be greater than 1 ether");
targetDailyCompoundRate = _targetDailyCompoundRate;
}
/// @dev updates the vault address variable
/// @param _vault address to send fees to
function changeVault(address _vault) external onlyOwner {
vault = _vault;
}
/// @dev deposits tokens into the farm
/// @param amount the amount of tokens to deposit
function deposit(uint amount) external whenNotPaused nonReentrant {
require(amount >= 1e18, "Must deposit at least 1 KRW");
update(); // distribute rewards
krw.safeTransferFrom(msg.sender, address(this), amount);
// subtract fee
if (fee != 0) {
uint feeAmount = (amount * fee) / 10000;
krw.safeTransfer(address(vault), feeAmount);
amount -= feeAmount;
}
// update user stake information
UserInfo storage user = stakes[msg.sender];
user.pastPending = getPending(msg.sender);
user.divisor = multiplier;
user.amount += amount;
totalStaked += amount;
emit Deposit(msg.sender, amount);
}
/// @dev withdraw tokens from the farm
/// @param amount the amount of tokens to withdraw
function withdraw(uint amount) public nonReentrant {
require(amount > 0, 'Amount must be larger than 0.');
require(stakes[msg.sender].amount >= amount, 'Amount cannot exceed balance.');
update(); // distribute rewards
// send rewards to user
uint pendingAmount = getPending(msg.sender);
totalPending -= pendingAmount;
krw.safeTransfer(msg.sender, pendingAmount);
// remove amount from user stake
UserInfo storage user = stakes[msg.sender];
totalStaked -= amount;
user.amount -= amount;
user.pastPending = 0;
user.divisor = user.amount == 0 ? 0 : multiplier;
// send amount to user
krw.safeTransfer(msg.sender, amount);
emit Withdraw(msg.sender, amount);
}
/// @dev withdraw all tokens from the farm
function withdrawAll() external {
withdraw(stakes[msg.sender].amount);
}
/// @dev withdraw all tokens from the farm, ignoring rewards
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = stakes[msg.sender];
// remove user stake and clear rewards
uint pendingAmount = getPending(msg.sender);
totalStaked -= user.amount;
totalPending -= pendingAmount;
user.amount = 0;
user.pastPending = 0;
user.divisor = 0;
// send tokens to user
krw.safeTransfer(msg.sender, user.amount);
emit EmergencyWithdraw(msg.sender, user.amount);
}
/// @dev claim rewards from the farm
function claim() external nonReentrant {
update(); // distribute rewards
// clear rewards from user information
UserInfo storage user = stakes[msg.sender];
uint pendingAmount = getPending( msg.sender);
totalPending -= pendingAmount;
user.divisor = multiplier;
user.pastPending = 0;
// send rewards to user
krw.safeTransfer(msg.sender, pendingAmount);
emit Claim(msg.sender, pendingAmount);
}
/// @dev updates the amount of rewards per block
function updateRewardsPerBlock() internal {
uint total = totalStaked + totalPending;
rewardsPerBlock = ((targetDailyCompoundRate - 1e18) * total) / dailyBlocks;
rewardsPerBlock = rewardsPerBlock < maxRewardsPerBlock ? rewardsPerBlock : maxRewardsPerBlock;
}
/// @dev distributes the rewards since update was last called
function update() public whenNotPaused {
if (totalStaked != 0) {
updateRewardsPerBlock();
uint blocksSinceLastReward = block.number < finalBlock ? (block.number - lastRewardBlock) : 0;
uint rewardsToDeliver = rewardsPerBlock * blocksSinceLastReward;
uint total = totalStaked + totalPending;
uint totalAfterRewards = total + rewardsToDeliver;
// If the multiplier is going to overflow, then end the reward distribution
// by setting the final block equal to the block number when rewards were last distributed.
// Then return, so that no rewards are distributed. Using this mechanism, people will be
// able to withdraw their stake and claim their rewards without any issues.
if (type(uint).max / totalAfterRewards < multiplier) {
multiplierIsMaxed = true;
finalBlock = lastRewardBlock;
return;
}
multiplier = (multiplier * totalAfterRewards) / total;
totalPending += rewardsToDeliver;
}
lastRewardBlock = block.number;
}
/// @dev calculates the rewards
/// @param account the account to calculate the rewards for
/// @return the rewards for the account
function getPending(address account) public view returns(uint) {
UserInfo memory user = stakes[account];
uint totalAmount = user.amount + user.pastPending;
return user.divisor == 0 ? 0 : (totalAmount * multiplier) / user.divisor - user.amount;
}
/// @dev pauses the farm
function pause() external onlyOwner {
_pause();
lastRewardBlock = block.number;
}
/// @dev resumes the farm
function unpause() external onlyOwner {
_unpause();
lastRewardBlock = block.number;
}
} | calculates and returns the APY | function getAPY() external view returns(uint) {
return totalStaked == 0 ? 0 : (rewardsPerBlock * dailyBlocks * 365) / (totalStaked + totalPending);
}
| 1,090,127 |
./partial_match/80001/0xEd494b640222d33F22a9156725d2a12a589fa3E0/sources/src/consensys_erc1400/ERC1400.sol | Token migration / Migrate contract. ===> CAUTION: DEFINITIVE ACTION This function shall be called once a new version of the smart contract has been created. Once this function is called: - The address of the new smart contract is set in ERC1820 registry - If the choice is definitive, the current smart contract is turned off and can never be used again newContractAddress Address of the new version of the smart contract. definitive If set to 'true' the contract is turned off definitely./ | function migrate(address newContractAddress, bool definitive)
external
onlyOwner
{
_migrate(newContractAddress, definitive);
}
| 8,796,180 |
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '@openzeppelin/contracts/utils/Counters.sol';
import '@openzeppelin/contracts/access/AccessControl.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721Burnable.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721Pausable.sol';
import './IERC721Creator.sol';
contract FirstDibsToken is ERC721, AccessControl, ERC721Burnable, ERC721Pausable, IERC721Creator {
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE');
bytes32 public constant PAUSER_ROLE = keccak256('PAUSER_ROLE');
/**
* @dev If greater than 0, then totalSupply will never exceed MAX_SUPPLY
* A value of 0 means there is no limit to the supply.
*/
uint256 public MAX_SUPPLY = 0;
/**
* @dev token ID mapping to payable creator address
*/
mapping(uint256 => address payable) private tokenCreators;
/**
* @dev Map token URI to a token ID
*/
mapping(string => uint256) private tokenUris;
/**
* @dev Auto-incrementing counter for token IDs
*/
Counters.Counter private tokenIds;
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract. Also sets `MAX_SUPPLY`.
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _maxSupply
) public ERC721(_name, _symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
// MAX_SUPPLY may only be set once
MAX_SUPPLY = _maxSupply;
}
/**
* @dev Internal function for setting the token's creator.
* @param _creator address of the creator of the token.
* @param _tokenId uint256 id of the token.
*/
function _setTokenCreator(address payable _creator, uint256 _tokenId) private {
tokenCreators[_tokenId] = _creator;
}
/**
* @dev Internal function for saving token URIs
* @param _tokenUri token URI string
* @param _tokenId uint256 id of the token.
*/
function _saveUniqueTokenURI(string memory _tokenUri, uint256 _tokenId) private {
require(tokenUris[_tokenUri] == 0, 'Duplicate token URIs not allowed');
tokenUris[_tokenUri] = _tokenId;
}
/**
* @dev External function to get the token's creator
* @param _tokenId uint256 id of the token.
*/
function tokenCreator(uint256 _tokenId) external view override returns (address payable) {
return tokenCreators[_tokenId];
}
/**
* @dev internal function that mints a token. Sets _creator to creator and owner.
* Checks MAX_SUPPLY against totalSupply and will not mint if totalSupply would exceed MAX_SUPPLY.
* @param _tokenURI uint256 metadata URI of the token.
* @param _creator address of the creator of the token.
*/
function _mint(string memory _tokenURI, address payable _creator) internal returns (uint256) {
require(MAX_SUPPLY == 0 || totalSupply() < MAX_SUPPLY, 'minted too many tokens');
tokenIds.increment();
uint256 newTokenId = tokenIds.current();
_saveUniqueTokenURI(_tokenURI, newTokenId);
_safeMint(_creator, newTokenId);
_setTokenURI(newTokenId, _tokenURI);
_setTokenCreator(_creator, newTokenId);
return newTokenId;
}
/**
* @dev Public function that mints a token. Sets msg.sender to creator and owner and requires MINTER_ROLE
* @param _tokenURI uint256 metadata URI of the token.
*/
function mint(string memory _tokenURI) public returns (uint256) {
require(hasRole(MINTER_ROLE, _msgSender()), 'mint: must have MINTER_ROLE');
return _mint(_tokenURI, _msgSender());
}
/**
* @dev Public function that allows admin to mint a token setting _creator to creator and owner
* @param _tokenURI uint256 metadata URI of the token.
* @param _creator address of the creator of the token.
*/
function mintWithCreator(string memory _tokenURI, address payable _creator)
public
returns (uint256)
{
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
'mintWithCreator: must have DEFAULT_ADMIN_ROLE'
);
return _mint(_tokenURI, _creator);
}
/**
* @dev Pauses all token transfers.
* See {ERC721Pausable} and {Pausable-_pause}.
* Requirements: the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), 'pause: must have PAUSER_ROLE');
_pause();
}
/**
* @dev Unpauses all token transfers.
* See {ERC721Pausable} and {Pausable-_unpause}.
* Requirements: the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), 'unpause: must have PAUSER_ROLE');
_unpause();
}
/**
* @dev Must override this function since both ERC721, ERC721Pausable define it
* Checks that the contract isn't paused before doing a transfer
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) internal override(ERC721, ERC721Pausable) {
ERC721Pausable._beforeTokenTransfer(_from, _to, _tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC721.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC721.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC721 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 ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
//SPDX-License-Identifier: BSD 3-Clause
pragma solidity 0.6.12;
/**
* @title IERC721 Non-Fungible Token Creator basic interface
* @dev Interop with other systems supporting this interface
* @notice Original license and source here: https://github.com/Pixura/pixura-contracts
*/
interface IERC721Creator {
/**
* @dev Gets the creator of the _tokenId
* @param _tokenId uint256 ID of the token
* @return address of the creator of _tokenId
*/
function tokenCreator(uint256 _tokenId) external view returns (address payable);
}
// 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.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// 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;
/*
* @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.2 <0.8.0;
import "../../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.6.2 <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.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// 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;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// 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.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_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());
}
}
| Internal function for saving token URIs _tokenUri token URI string _tokenId uint256 id of the token./ | function _saveUniqueTokenURI(string memory _tokenUri, uint256 _tokenId) private {
require(tokenUris[_tokenUri] == 0, 'Duplicate token URIs not allowed');
tokenUris[_tokenUri] = _tokenId;
}
| 6,019,257 |
// SPDX-License-Identifier: MIT
/**
* █▄ █ █▀ ▀█▀ ▄▀▀ ▄▀▄ █ █ ██▀ ▄▀▀ ▀█▀ █ ▄▀▄ █▄ █ ▄▀▀
* █ ▀█ █▀ █ ▀▄▄ ▀▄▀ █▄▄ █▄▄ █▄▄ ▀▄▄ █ █ ▀▄▀ █ ▀█ ▄██
*
* Made with 🧡 by Kreation.tech
*/
pragma solidity ^0.8.6;
import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import {IERC2981Upgradeable, IERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {CountersUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
/**
* This contract allows dynamic NFT minting.
*
* Operations allow for selling publicly, partial or total giveaways, direct giveaways and rewardings.
*/
contract DroppableCollection is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
event ItemsAdded(uint256 amount);
struct Info {
// name of the collection
string name;
// symbol of the tokens minted by this contract
string symbol;
// description of the collection
string description;
}
// collection description
string public description;
// collection base URL
string public baseUrl;
// the number of nft this collection contains
uint64 public size;
// royalties ERC2981 in bps
uint16 public royalties;
constructor() initializer { }
/**
* Creates a new collection and builds all the available NFTS setting their owner to the address that creates the edition: this can be re-assigned or updated later.
*
* @param _owner can drop more tokens, gets royalties and can update the base URL.
* @param _info collection properties
* @param _size number of NFTs that can be minted from this contract: set to 0 for unbound
* @param _baseUrl sad
* @param _royalties perpetual royalties paid to the creator upon token selling
*/
function initialize(
address _owner,
Info memory _info,
uint64 _size,
string memory _baseUrl,
uint16 _royalties
) public initializer {
__ERC721_init(_info.name, _info.symbol);
__Ownable_init();
transferOwnership(_owner); // set ownership
description = _info.description;
require(bytes(_baseUrl).length > 0, "Empty base URL");
baseUrl = _baseUrl;
if (_size > 0) {
_mint(_size);
}
require(_royalties < 10_000, "Royalties too high");
royalties = _royalties;
}
/**
* Returns the number of tokens minted so far
*/
function totalSupply() public view returns (uint256) {
return size;
}
function drop(string memory _baseUrl, uint64 _size) external onlyOwner returns (uint256) {
baseUrl = _baseUrl;
return _mint(_size);
}
function _mint(uint64 _size) internal returns (uint256) {
require(_size > size, "Not extended");
for (uint64 tokenId = size + 1; tokenId <= _size; tokenId++) {
_safeMint(owner(), tokenId, "");
}
size = _size;
return size;
}
/**
* User burn function for token id.
*
* @param tokenId token edition identifier to burn
*/
function burn(uint256 tokenId) external {
require(_isApprovedOrOwner(_msgSender(), tokenId), "Not approved");
_burn(tokenId);
}
/**
* Get URI for given token id
*
* @param tokenId token id to get uri for
* @return base64-encoded json metadata object
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "Token doesn't exist");
return string(abi.encodePacked(baseUrl, "/", tokenId, ".json"));
}
/**
* ERC2981 - Gets royalty information for token
*
* @param _value the sale price for this token
*/
function royaltyInfo(uint256, uint256 _value) external view override returns (address receiver, uint256 royaltyAmount) {
if (owner() == address(0x0)) {
return (owner(), 0);
}
return (owner(), (_value * royalties) / 10_000);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) {
return type(IERC2981Upgradeable).interfaceId == interfaceId || ERC721Upgradeable.supportsInterface(interfaceId);
}
}
| Get URI for given token id tokenId token id to get uri for return base64-encoded json metadata object/ | function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "Token doesn't exist");
return string(abi.encodePacked(baseUrl, "/", tokenId, ".json"));
}
| 12,643,566 |
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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.7.6;
interface ILiquidator {
function liquidate(
address recipient,
address from,
address to,
uint256 amount,
uint256 minOut
) external returns (uint256);
function getSwapInfo(address from, address to) external view returns (address router, address[] memory path);
function sushiswapRouter() external view returns (address);
function uniswapRouter() external view returns (address);
function weth() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IManager {
function token() external view returns (address);
function buybackFee() external view returns (uint256);
function managementFee() external view returns (uint256);
function liquidators(address from, address to) external view returns (address);
function whitelisted(address _contract) external view returns (bool);
function banks(uint256 i) external view returns (address);
function totalBanks() external view returns (uint256);
function strategies(address bank, uint256 i) external view returns (address);
function totalStrategies(address bank) external view returns (uint256);
function withdrawIndex(address bank) external view returns (uint256);
function setWithdrawIndex(uint256 i) external;
function rebalance(address bank) external;
function finance(address bank) external;
function financeAll(address bank) external;
function buyback(address from) external;
function accrueRevenue(
address bank,
address underlying,
uint256 amount
) external;
function exitAll(address bank) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IRegistry {
function governance() external view returns (address);
function manager() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ISubscriber {
function registry() external view returns (address);
function governance() external view returns (address);
function manager() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {IBankStorage} from "./IBankStorage.sol";
interface IBank is IBankStorage {
function strategies(uint256 i) external view returns (address);
function totalStrategies() external view returns (uint256);
function underlyingBalance() external view returns (uint256);
function strategyBalance(uint256 i) external view returns (uint256);
function investedBalance() external view returns (uint256);
function virtualBalance() external view returns (uint256);
function virtualPrice() external view returns (uint256);
function pause() external;
function unpause() external;
function invest(address strategy, uint256 amount) external;
function investAll(address strategy) external;
function exit(address strategy, uint256 amount) external;
function exitAll(address strategy) external;
function deposit(uint256 amount) external;
function depositFor(uint256 amount, address recipient) external;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IBankStorage {
function paused() external view returns (bool);
function underlying() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {IStrategyBase} from "./IStrategyBase.sol";
interface IStrategy is IStrategyBase {
function investedBalance() external view returns (uint256);
function invest() external;
function withdraw(uint256 amount) external returns (uint256);
function withdrawAll() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {IStrategyStorage} from "./IStrategyStorage.sol";
interface IStrategyBase is IStrategyStorage {
function underlyingBalance() external view returns (uint256);
function derivativeBalance() external view returns (uint256);
function rewardBalance() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IStrategyStorage {
function bank() external view returns (address);
function underlying() external view returns (address);
function derivative() external view returns (address);
function reward() external view returns (address);
// function investedBalance() external view returns (uint256);
// function invest() external;
// function withdraw(uint256 amount) external returns (uint256);
// function withdrawAll() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ICurve3PoolStrategyStorage {
function pool() external view returns (address);
function gauge() external view returns (address);
function mintr() external view returns (address);
function index() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library TransferHelper {
using SafeERC20 for IERC20;
// safely transfer tokens without underflowing
function safeTokenTransfer(
address recipient,
address token,
uint256 amount
) internal returns (uint256) {
if (amount == 0) {
return 0;
}
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance < amount) {
IERC20(token).safeTransfer(recipient, balance);
return balance;
} else {
IERC20(token).safeTransfer(recipient, amount);
return amount;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/// @title Oh! Finance Base Upgradeable
/// @notice Contains internal functions to get/set primitive data types used by a proxy contract
abstract contract OhUpgradeable {
function getAddress(bytes32 slot) internal view returns (address _address) {
// solhint-disable-next-line no-inline-assembly
assembly {
_address := sload(slot)
}
}
function getBoolean(bytes32 slot) internal view returns (bool _bool) {
uint256 bool_;
// solhint-disable-next-line no-inline-assembly
assembly {
bool_ := sload(slot)
}
_bool = bool_ == 1;
}
function getBytes32(bytes32 slot) internal view returns (bytes32 _bytes32) {
// solhint-disable-next-line no-inline-assembly
assembly {
_bytes32 := sload(slot)
}
}
function getUInt256(bytes32 slot) internal view returns (uint256 _uint) {
// solhint-disable-next-line no-inline-assembly
assembly {
_uint := sload(slot)
}
}
function setAddress(bytes32 slot, address _address) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _address)
}
}
function setBytes32(bytes32 slot, bytes32 _bytes32) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _bytes32)
}
}
/// @dev Set a boolean storage variable in a given slot
/// @dev Convert to a uint to take up an entire contract storage slot
function setBoolean(bytes32 slot, bool _bool) internal {
uint256 bool_ = _bool ? 1 : 0;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, bool_)
}
}
function setUInt256(bytes32 slot, uint256 _uint) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _uint)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ISubscriber} from "../interfaces/ISubscriber.sol";
import {IRegistry} from "../interfaces/IRegistry.sol";
import {OhUpgradeable} from "../proxy/OhUpgradeable.sol";
/// @title Oh! Finance Subscriber Upgradeable
/// @notice Base Oh! Finance upgradeable contract used to control access throughout the protocol
abstract contract OhSubscriberUpgradeable is Initializable, OhUpgradeable, ISubscriber {
bytes32 private constant _REGISTRY_SLOT = 0x1b5717851286d5e98a28354be764b8c0a20eb2fbd059120090ee8bcfe1a9bf6c;
/// @notice Only allow authorized addresses (governance or manager) to execute a function
modifier onlyAuthorized {
require(msg.sender == governance() || msg.sender == manager(), "Subscriber: Only Authorized");
_;
}
/// @notice Only allow the governance address to execute a function
modifier onlyGovernance {
require(msg.sender == governance(), "Subscriber: Only Governance");
_;
}
/// @notice Verify the registry storage slot is correct
constructor() {
assert(_REGISTRY_SLOT == bytes32(uint256(keccak256("eip1967.subscriber.registry")) - 1));
}
/// @notice Initialize the Subscriber
/// @param registry_ The Registry contract address
/// @dev Always call this method in the initializer function for any derived classes
function initializeSubscriber(address registry_) internal initializer {
require(Address.isContract(registry_), "Subscriber: Invalid Registry");
_setRegistry(registry_);
}
/// @notice Set the Registry for the contract. Only callable by Governance.
/// @param registry_ The new registry
/// @dev Requires sender to be Governance of the new Registry to avoid bricking.
/// @dev Ideally should not be used
function setRegistry(address registry_) external onlyGovernance {
_setRegistry(registry_);
require(msg.sender == governance(), "Subscriber: Bad Governance");
}
/// @notice Get the Governance address
/// @return The current Governance address
function governance() public view override returns (address) {
return IRegistry(registry()).governance();
}
/// @notice Get the Manager address
/// @return The current Manager address
function manager() public view override returns (address) {
return IRegistry(registry()).manager();
}
/// @notice Get the Registry address
/// @return The current Registry address
function registry() public view override returns (address) {
return getAddress(_REGISTRY_SLOT);
}
function _setRegistry(address registry_) private {
setAddress(_REGISTRY_SLOT, registry_);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {IBank} from "../interfaces/bank/IBank.sol";
import {IStrategyBase} from "../interfaces/strategies/IStrategyBase.sol";
import {ILiquidator} from "../interfaces/ILiquidator.sol";
import {IManager} from "../interfaces/IManager.sol";
import {TransferHelper} from "../libraries/TransferHelper.sol";
import {OhSubscriberUpgradeable} from "../registry/OhSubscriberUpgradeable.sol";
import {OhStrategyStorage} from "./OhStrategyStorage.sol";
/// @title Oh! Finance Strategy
/// @notice Base Upgradeable Strategy Contract to build strategies on
contract OhStrategy is OhSubscriberUpgradeable, OhStrategyStorage, IStrategyBase {
using SafeERC20 for IERC20;
event Liquidate(address indexed router, address indexed token, uint256 amount);
event Sweep(address indexed token, uint256 amount, address recipient);
/// @notice Only the Bank can execute these functions
modifier onlyBank() {
require(msg.sender == bank(), "Strategy: Only Bank");
_;
}
/// @notice Initialize the base Strategy
/// @param registry_ Address of the Registry
/// @param bank_ Address of Bank
/// @param underlying_ Underying token that is deposited
/// @param derivative_ Derivative token received from protocol, or address(0)
/// @param reward_ Reward token received from protocol, or address(0)
function initializeStrategy(
address registry_,
address bank_,
address underlying_,
address derivative_,
address reward_
) internal initializer {
initializeSubscriber(registry_);
initializeStorage(bank_, underlying_, derivative_, reward_);
}
/// @dev Balance of underlying awaiting Strategy investment
function underlyingBalance() public view override returns (uint256) {
return IERC20(underlying()).balanceOf(address(this));
}
/// @dev Balance of derivative tokens received from Strategy, if applicable
/// @return The balance of derivative tokens
function derivativeBalance() public view override returns (uint256) {
if (derivative() == address(0)) {
return 0;
}
return IERC20(derivative()).balanceOf(address(this));
}
/// @dev Balance of reward tokens awaiting liquidation, if applicable
function rewardBalance() public view override returns (uint256) {
if (reward() == address(0)) {
return 0;
}
return IERC20(reward()).balanceOf(address(this));
}
/// @notice Governance function to sweep any stuck / airdrop tokens to a given recipient
/// @param token The address of the token to sweep
/// @param amount The amount of tokens to sweep
/// @param recipient The address to send the sweeped tokens to
function sweep(
address token,
uint256 amount,
address recipient
) external onlyGovernance {
// require(!_protected[token], "Strategy: Cannot sweep");
TransferHelper.safeTokenTransfer(recipient, token, amount);
emit Sweep(token, amount, recipient);
}
/// @dev Liquidation function to swap rewards for underlying
function liquidate(
address from,
address to,
uint256 amount
) internal {
// if (amount > minimumSell())
// find the liquidator to use
address manager = manager();
address liquidator = IManager(manager).liquidators(from, to);
// increase allowance and liquidate to the manager
TransferHelper.safeTokenTransfer(liquidator, from, amount);
uint256 received = ILiquidator(liquidator).liquidate(manager, from, to, amount, 1);
// notify revenue and transfer proceeds back to strategy
IManager(manager).accrueRevenue(bank(), to, received);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {IStrategyStorage} from "../interfaces/strategies/IStrategyStorage.sol";
import {OhUpgradeable} from "../proxy/OhUpgradeable.sol";
contract OhStrategyStorage is Initializable, OhUpgradeable, IStrategyStorage {
bytes32 internal constant _BANK_SLOT = 0xd2eff96e29993ca5431993c3a205e12e198965c0e1fdd87b4899b57f1e611c74;
bytes32 internal constant _UNDERLYING_SLOT = 0x0fad97fe3ec7d6c1e9191a09a0c4ccb7a831b6605392e57d2fedb8501a4dc812;
bytes32 internal constant _DERIVATIVE_SLOT = 0x4ff4c9b81c0bf267e01129f4817e03efc0163ee7133b87bd58118a96bbce43d3;
bytes32 internal constant _REWARD_SLOT = 0xaeb865605058f37eedb4467ee2609ddec592b0c9a6f7f7cb0db3feabe544c71c;
constructor() {
assert(_BANK_SLOT == bytes32(uint256(keccak256("eip1967.strategy.bank")) - 1));
assert(_UNDERLYING_SLOT == bytes32(uint256(keccak256("eip1967.strategy.underlying")) - 1));
assert(_DERIVATIVE_SLOT == bytes32(uint256(keccak256("eip1967.strategy.derivative")) - 1));
assert(_REWARD_SLOT == bytes32(uint256(keccak256("eip1967.strategy.reward")) - 1));
}
function initializeStorage(
address bank_,
address underlying_,
address derivative_,
address reward_
) internal initializer {
_setBank(bank_);
_setUnderlying(underlying_);
_setDerivative(derivative_);
_setReward(reward_);
}
/// @notice The Bank that the Strategy is associated with
function bank() public view override returns (address) {
return getAddress(_BANK_SLOT);
}
/// @notice The underlying token the Strategy invests in AaveV2
function underlying() public view override returns (address) {
return getAddress(_UNDERLYING_SLOT);
}
/// @notice The derivative token received from AaveV2 (aToken)
function derivative() public view override returns (address) {
return getAddress(_DERIVATIVE_SLOT);
}
/// @notice The reward token received from AaveV2 (stkAave)
function reward() public view override returns (address) {
return getAddress(_REWARD_SLOT);
}
function _setBank(address _address) internal {
setAddress(_BANK_SLOT, _address);
}
function _setUnderlying(address _address) internal {
setAddress(_UNDERLYING_SLOT, _address);
}
function _setDerivative(address _address) internal {
setAddress(_DERIVATIVE_SLOT, _address);
}
function _setReward(address _address) internal {
setAddress(_REWARD_SLOT, _address);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {ICurve3Pool} from "./interfaces/ICurve3Pool.sol";
import {IGauge} from "./interfaces/IGauge.sol";
import {IMintr} from "./interfaces/IMintr.sol";
/// @title Oh! Finance Curve 3Pool Helper
/// @notice Helper functions for Curve 3Pool Strategies
abstract contract OhCurve3PoolHelper {
using SafeERC20 for IERC20;
/// @notice Add liquidity to Curve's 3Pool, receiving 3CRV in return
/// @param pool The address of Curve 3Pool
/// @param underlying The underlying we want to deposit
/// @param index The index of the underlying
/// @param amount The amount of underlying to deposit
/// @param minMint The min LP tokens to mint before tx reverts (slippage)
function addLiquidity(
address pool,
address underlying,
uint256 index,
uint256 amount,
uint256 minMint
) internal {
uint256[3] memory amounts = [uint256(0), uint256(0), uint256(0)];
amounts[index] = amount;
IERC20(underlying).safeIncreaseAllowance(pool, amount);
ICurve3Pool(pool).add_liquidity(amounts, minMint);
}
/// @notice Remove liquidity from Curve 3Pool, receiving a single underlying
/// @param pool The Curve 3Pool
/// @param index The index of underlying we want to withdraw
/// @param amount The amount to withdraw
/// @param maxBurn The max LP tokens to burn before the tx reverts (slippage)
function removeLiquidity(
address pool,
uint256 index,
uint256 amount,
uint256 maxBurn
) internal {
uint256[3] memory amounts = [uint256(0), uint256(0), uint256(0)];
amounts[index] = amount;
ICurve3Pool(pool).remove_liquidity_imbalance(amounts, maxBurn);
}
/// @notice Claim CRV rewards from the Mintr for a given Gauge
/// @param mintr The CRV Mintr (Rewards Contract)
/// @param gauge The Gauge (Staking Contract) to claim from
function claim(address mintr, address gauge) internal {
IMintr(mintr).mint(gauge);
}
/// @notice Calculate the max withdrawal amount to a single underlying
/// @param pool The Curve LP Pool
/// @param amount The amount of underlying to deposit
/// @param index The index of the underlying in the LP Pool
function calcWithdraw(
address pool,
uint256 amount,
int128 index
) internal view returns (uint256) {
return ICurve3Pool(pool).calc_withdraw_one_coin(amount, index);
}
/// @notice Get the balance of staked tokens in a given Gauge
/// @param gauge The Curve Gauge to check
function staked(address gauge) internal view returns (uint256) {
return IGauge(gauge).balanceOf(address(this));
}
/// @notice Stake crvUnderlying into the Gauge to earn CRV
/// @param gauge The Curve Gauge to stake into
/// @param crvUnderlying The Curve LP Token to stake
/// @param amount The amount of LP Tokens to stake
function stake(
address gauge,
address crvUnderlying,
uint256 amount
) internal {
IERC20(crvUnderlying).safeIncreaseAllowance(gauge, amount);
IGauge(gauge).deposit(amount);
}
/// @notice Unstake crvUnderlying funds from the Curve Gauge
/// @param gauge The Curve Gauge to unstake from
/// @param amount The amount of LP Tokens to withdraw
function unstake(address gauge, uint256 amount) internal {
IGauge(gauge).withdraw(amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {Math} from "@openzeppelin/contracts/math/Math.sol";
import {IStrategy} from "../../interfaces/strategies/IStrategy.sol";
import {TransferHelper} from "../../libraries/TransferHelper.sol";
import {OhStrategy} from "../OhStrategy.sol";
import {OhCurve3PoolHelper} from "./OhCurve3PoolHelper.sol";
import {OhCurve3PoolStrategyStorage} from "./OhCurve3PoolStrategyStorage.sol";
/// @title Oh! Finance Curve 3Pool Strategy
/// @notice Standard Curve 3Pool LP + Gauge Single Underlying Strategy
/// @notice 3Pool Underlying, in order: (DAI, USDC, USDT)
contract OhCurve3PoolStrategy is OhStrategy, OhCurve3PoolStrategyStorage, OhCurve3PoolHelper, IStrategy {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/// @notice Initialize the Curve 3Pool Strategy Logic
constructor() initializer {
assert(registry() == address(0));
assert(bank() == address(0));
assert(underlying() == address(0));
assert(reward() == address(0));
}
/// @notice Initialize the Curve 3Pool Strategy Proxy
/// @param registry_ Address of the Registry
/// @param bank_ Address of the Bank
/// @param underlying_ Underlying (DAI, USDC, USDT)
/// @param derivative_ 3CRV LP Token
/// @param reward_ CRV Gov Token
/// @param pool_ Address of the Curve 3Pool
/// @param gauge_ Curve Gauge, Staking Contract
/// @param mintr_ Curve Mintr, Rewards Contract
/// @param index_ Underlying 3Pool Index
function initializeCurve3PoolStrategy(
address registry_,
address bank_,
address underlying_,
address derivative_,
address reward_,
address pool_,
address gauge_,
address mintr_,
uint256 index_
) public initializer {
initializeStrategy(registry_, bank_, underlying_, derivative_, reward_);
initializeCurve3PoolStorage(pool_, gauge_, mintr_, index_);
}
// calculate the total underlying balance
function investedBalance() public view override returns (uint256) {
return calcWithdraw(pool(), stakedBalance(), int128(index()));
}
// amount of 3CRV staked in the Gauge
function stakedBalance() public view returns (uint256) {
return staked(gauge());
}
/// @notice Execute the Curve 3Pool Strategy
/// @dev Compound CRV Yield, Add Liquidity, Stake into Gauge
function invest() external override onlyBank {
_compound();
_deposit();
}
/// @notice Withdraw an amount of underlying from Curve 3Pool Strategy
/// @param amount Amount of Underlying tokens to withdraw
/// @dev Unstake from Gauge, Remove Liquidity
function withdraw(uint256 amount) external override onlyBank returns (uint256) {
uint256 withdrawn = _withdraw(msg.sender, amount);
return withdrawn;
}
/// @notice Withdraw all underlying from Curve 3Pool Strategy
/// @dev Unstake from Gauge, Remove Liquidity
function withdrawAll() external override onlyBank {
uint256 invested = investedBalance();
_withdraw(msg.sender, invested);
}
/// @dev Compound rewards into underlying through liquidation
/// @dev Claim Rewards from Mintr, sell CRV for USDC
function _compound() internal {
// claim available CRV rewards
claim(mintr(), gauge());
uint256 rewardAmount = rewardBalance();
if (rewardAmount > 0) {
liquidate(reward(), underlying(), rewardAmount);
}
}
// deposit underlying into 3Pool to get 3CRV and stake into Gauge
function _deposit() internal {
uint256 amount = underlyingBalance();
if (amount > 0) {
// add liquidity to 3Pool to receive 3CRV
addLiquidity(pool(), underlying(), index(), amount, 1);
// stake all received in the 3CRV gauge
stake(gauge(), derivative(), derivativeBalance());
}
}
// withdraw underlying tokens from the protocol
// TODO: Double check withdrawGauge math, TransferHelper
function _withdraw(address recipient, uint256 amount) internal returns (uint256) {
if (amount == 0) {
return 0;
}
uint256 invested = investedBalance();
uint256 staked = stakedBalance();
// calculate % of supply ownership
uint256 supplyShare = amount.mul(1e18).div(invested);
// find amount to unstake in 3CRV
uint256 unstakeAmount = Math.min(staked, supplyShare.mul(staked).div(1e18));
// find amount to redeem in underlying
uint256 redeemAmount = Math.min(invested, supplyShare.mul(invested).div(1e18));
// unstake from Gauge & remove liquidity from Pool
unstake(gauge(), unstakeAmount);
removeLiquidity(pool(), index(), redeemAmount, unstakeAmount);
// withdraw to bank
uint256 withdrawn = TransferHelper.safeTokenTransfer(recipient, underlying(), amount);
return withdrawn;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {ICurve3PoolStrategyStorage} from "../../interfaces/strategies/curve/ICurve3PoolStrategyStorage.sol";
import {OhUpgradeable} from "../../proxy/OhUpgradeable.sol";
contract OhCurve3PoolStrategyStorage is Initializable, OhUpgradeable, ICurve3PoolStrategyStorage {
bytes32 internal constant _POOL_SLOT = 0x6c9960513c6769ea8f48802ea7b637e9ce937cc3d022135cc43626003296fc46;
bytes32 internal constant _GAUGE_SLOT = 0x85c79ab2dc779eb860ec993658b7f7a753e59bdfda156c7391620a5f513311e6;
bytes32 internal constant _MINTR_SLOT = 0x3e7777dca2f9f31e4c2d62ce76af8def0f69b868d665539787b25b39a9f7224f;
bytes32 internal constant _INDEX_SLOT = 0xd5700a843c20bfe827ca47a7c73f83287e1b32b3cd4ac659d79f800228d617fd;
constructor() {
assert(_POOL_SLOT == bytes32(uint256(keccak256("eip1967.curve3PoolStrategy.pool")) - 1));
assert(_GAUGE_SLOT == bytes32(uint256(keccak256("eip1967.curve3PoolStrategy.gauge")) - 1));
assert(_MINTR_SLOT == bytes32(uint256(keccak256("eip1967.curve3PoolStrategy.mintr")) - 1));
assert(_INDEX_SLOT == bytes32(uint256(keccak256("eip1967.curve3PoolStrategy.index")) - 1));
}
function initializeCurve3PoolStorage(
address pool_,
address gauge_,
address mintr_,
uint256 index_
) internal initializer {
_setPool(pool_);
_setGauge(gauge_);
_setMintr(mintr_);
_setIndex(index_);
}
function pool() public view override returns (address) {
return getAddress(_POOL_SLOT);
}
function gauge() public view override returns (address) {
return getAddress(_GAUGE_SLOT);
}
function mintr() public view override returns (address) {
return getAddress(_MINTR_SLOT);
}
function index() public view override returns (uint256) {
return getUInt256(_INDEX_SLOT);
}
function _setPool(address pool_) internal {
setAddress(_POOL_SLOT, pool_);
}
function _setGauge(address gauge_) internal {
setAddress(_GAUGE_SLOT, gauge_);
}
function _setMintr(address mintr_) internal {
setAddress(_MINTR_SLOT, mintr_);
}
function _setIndex(uint256 index_) internal {
setUInt256(_INDEX_SLOT, index_);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ICurve3Pool {
function calc_token_amount(uint256[3] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256, int128) external view returns (uint256);
function get_virtual_price() external view returns (uint256);
function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external;
function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount)
external;
function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IGauge {
function deposit(uint256) external;
function balanceOf(address) external view returns (uint256);
function withdraw(uint256) external;
function user_checkpoint(address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IMintr {
function mint(address) external;
} | Governance function to sweep any stuck / airdrop tokens to a given recipient token The address of the token to sweep amount The amount of tokens to sweep recipient The address to send the sweeped tokens to require(!_protected[token], "Strategy: Cannot sweep"); | function sweep(
address token,
uint256 amount,
address recipient
) external onlyGovernance {
TransferHelper.safeTokenTransfer(recipient, token, amount);
emit Sweep(token, amount, recipient);
}
| 273,963 |
./full_match/1/0x2a132928479a25F1d94387b12CA2A043558C3C89/sources/browser/tnifarming.sol | Update reward variables of the given pool to be up-to-date. _pid ID of a specific LP token pool. See index of PoolInfo[]./ | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tniReward = multiplier.mul(tniPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accTniPerShare = pool.accTniPerShare.add(tniReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 3,121,627 |
pragma solidity 0.4.26;
import './Owned.sol';
import './interfaces/IAddressList.sol';
/**
* @dev Non standard token registry
*
* manages tokens who don't return true/false on transfer/transferFrom/approve but revert on failure instead
*/
contract NonStandardTokenRegistry is IAddressList, Owned {
mapping (address => bool) public listedAddresses;
/**
* @dev initializes a new NonStandardTokenRegistry instance
*/
constructor() public {
}
/**
* @dev registers/unregisters a new non standard ERC20 token in the registry
*
* @param token token address
* @param register true to register the token, false to remove it
*/
function setAddress(address token, bool register) public ownerOnly {
listedAddresses[token] = register;
}
} | registers/unregisters a new non standard ERC20 token in the registry token token address register true to register the token, false to remove it/ | function setAddress(address token, bool register) public ownerOnly {
listedAddresses[token] = register;
}
| 6,454,618 |
./partial_match/1/0xd57d5d1dd984C6d6Fe074C070A7EFf9a69fd3667/sources/contracts/Phase4_Playground-0.sol | allows token owners to decide if they want goodies in their image check if token exists ensure that msg.sender is token owner update goodies | function toggleTokenGoodies(uint256 _tokenId) public
{
if(!_exists(_tokenId)) revert ThisTokenIsLostInSpace();
if(msg.sender != ownerOf(_tokenId)) revert WhoaFriendCantUpdateGoodiesForTokensYouDontOwn();
TokenToGoodiesMap[_tokenId] = !TokenToGoodiesMap[_tokenId];
}
| 2,820,278 |
pragma solidity ^0.5.2;
import "./lib/Ownable.sol";
import "./lib/SafeMath.sol";
import "./IERC20Seed.sol";
import "./IAdminTools.sol";
import "./IATDeployer.sol";
import "./ITDeployer.sol";
import "./IFPDeployer.sol";
contract Factory is Ownable {
using SafeMath for uint256;
address[] public deployerList;
uint public deployerLength;
address[] public ATContractsList;
address[] public TContractsList;
address[] public FPContractsList;
mapping(address => bool) public deployers;
mapping(address => bool) public ATContracts;
mapping(address => bool) public TContracts;
mapping(address => bool) public FPContracts;
IERC20Seed private seedContract;
address private seedAddress;
IATDeployer private deployerAT;
address private ATDAddress;
ITDeployer private deployerT;
address private TDAddress;
IFPDeployer private deployerFP;
address private FPDAddress;
address private internalDEXAddress;
uint private factoryDeployBlock;
event NewPanelCreated(address, address, address, address, uint);
event ATFactoryAddressChanged();
event TFactoryAddressChanged();
event FPFactoryAddressChanged();
event InternalDEXAddressChanged();
constructor (address _seedAddress, address _ATDAddress, address _TDAddress, address _FPDAddress) public {
seedAddress = _seedAddress;
seedContract = IERC20Seed(seedAddress);
ATDAddress = _ATDAddress;
deployerAT = IATDeployer(ATDAddress);
TDAddress = _TDAddress;
deployerT = ITDeployer(_TDAddress);
FPDAddress = _FPDAddress;
deployerFP = IFPDeployer(_FPDAddress);
factoryDeployBlock = block.number;
}
/**
* @dev change AdminTols deployer address
* @param _newATD new AT deployer address
*/
function changeATFactoryAddress(address _newATD) external onlyOwner {
require(block.number < 8850000, "Time expired!");
require(_newATD != address(0), "Address not suitable!");
require(_newATD != ATDAddress, "AT factory address not changed!");
ATDAddress = _newATD;
deployerAT = IATDeployer(ATDAddress);
emit ATFactoryAddressChanged();
}
/**
* @dev change Token deployer address
* @param _newTD new T deployer address
*/
function changeTDeployerAddress(address _newTD) external onlyOwner {
require(block.number < 8850000, "Time expired!");
require(_newTD != address(0), "Address not suitable!");
require(_newTD != TDAddress, "AT factory address not changed!");
TDAddress = _newTD;
deployerT = ITDeployer(TDAddress);
emit TFactoryAddressChanged();
}
/**
* @dev change Funding Panel deployer address
* @param _newFPD new FP deployer address
*/
function changeFPDeployerAddress(address _newFPD) external onlyOwner {
require(block.number < 8850000, "Time expired!");
require(_newFPD != address(0), "Address not suitable!");
require(_newFPD != ATDAddress, "AT factory address not changed!");
FPDAddress = _newFPD;
deployerFP = IFPDeployer(FPDAddress);
emit FPFactoryAddressChanged();
}
/**
* @dev set internal DEX address
* @param _dexAddress internal DEX address
*/
function setInternalDEXAddress(address _dexAddress) external onlyOwner {
require(block.number < 8850000, "Time expired!");
require(_dexAddress != address(0), "Address not suitable!");
require(_dexAddress != internalDEXAddress, "AT factory address not changed!");
internalDEXAddress = _dexAddress;
emit InternalDEXAddressChanged();
}
/**
* @dev deploy a new set of contracts for the Panel, with all params needed by contracts. Set the minter address for Token contract,
* Owner is set as a manager in WL, Funding and FundsUnlocker, DEX is whitelisted
* @param _name name of the token to be deployed
* @param _symbol symbol of the token to be deployed
* @param _setDocURL URL of the document describing the Panel
* @param _setDocHash hash of the document describing the Panel
* @param _exchRateSeed exchange rate between SEED tokens received and tokens given to the SEED sender (multiply by 10^_exchRateDecim)
* @param _exchRateOnTop exchange rate between SEED token received and tokens minted on top (multiply by 10^_exchRateDecim)
* @param _seedMaxSupply max supply of SEED tokens accepted by this contract
* @param _WLAnonymThr max anonym threshold
*/
function deployPanelContracts(string memory _name, string memory _symbol, string memory _setDocURL, bytes32 _setDocHash,
uint256 _exchRateSeed, uint256 _exchRateOnTop, uint256 _seedMaxSupply, uint256 _WLAnonymThr) public {
address sender = msg.sender;
require(sender != address(0), "Sender Address is zero");
require(internalDEXAddress != address(0), "Internal DEX Address is zero");
deployers[sender] = true;
deployerList.push(sender);
deployerLength = deployerList.length;
address newAT = deployerAT.newAdminTools(_WLAnonymThr);
ATContracts[newAT] = true;
ATContractsList.push(newAT);
address newT = deployerT.newToken(sender, _name, _symbol, newAT);
TContracts[newT] = true;
TContractsList.push(newT);
address newFP = deployerFP.newFundingPanel(sender, _setDocURL, _setDocHash, _exchRateSeed, _exchRateOnTop,
seedAddress, _seedMaxSupply, newT, newAT, (deployerLength-1));
FPContracts[newFP] = true;
FPContractsList.push(newFP);
IAdminTools ATBrandNew = IAdminTools(newAT);
ATBrandNew.setFFPAddresses(address(this), newFP);
ATBrandNew.setMinterAddress(newFP);
ATBrandNew.addWLManagers(address(this));
ATBrandNew.addWLManagers(sender);
ATBrandNew.addFundingManagers(sender);
ATBrandNew.addFundsUnlockerManagers(sender);
ATBrandNew.setWalletOnTopAddress(sender);
uint256 dexMaxAmnt = _exchRateSeed.mul(300000000); //Seed total supply
ATBrandNew.addToWhitelist(internalDEXAddress, dexMaxAmnt);
uint256 onTopMaxAmnt = _seedMaxSupply.mul(_exchRateSeed).div(10**18);
ATBrandNew.addToWhitelist(sender, onTopMaxAmnt);
ATBrandNew.removeWLManagers(address(this));
Ownable customOwnable = Ownable(newAT);
customOwnable.transferOwnership(sender);
emit NewPanelCreated(sender, newAT, newT, newFP, deployerLength);
}
/**
* @dev get deployers number
*/
function getTotalDeployer() external view returns(uint256) {
return deployerList.length;
}
/**
* @dev get AT contracts number
*/
function getTotalATContracts() external view returns(uint256) {
return ATContractsList.length;
}
/**
* @dev get T contracts number
*/
function getTotalTContracts() external view returns(uint256) {
return TContractsList.length;
}
/**
* @dev get FP contracts number
*/
function getTotalFPContracts() external view returns(uint256) {
return FPContractsList.length;
}
/**
* @dev get if address is a deployer
*/
function isFactoryDeployer(address _addr) external view returns(bool) {
return deployers[_addr];
}
/**
* @dev get if address is an AT contract generated by factory
*/
function isFactoryATGenerated(address _addr) external view returns(bool) {
return ATContracts[_addr];
}
/**
* @dev get if address is a T contract generated by factory
*/
function isFactoryTGenerated(address _addr) external view returns(bool) {
return TContracts[_addr];
}
/**
* @dev get if address is a T contract generated by factory
*/
function isFactoryFPGenerated(address _addr) external view returns(bool) {
return FPContracts[_addr];
}
/**
* @dev get the i-th element in every array
*/
function getContractsByIndex(uint256 _index) external view returns (address, address, address, address) {
return(deployerList[_index], ATContractsList[_index], TContractsList[_index], FPContractsList[_index]);
}
/**
* @dev get the i-th element in FPContractsList array
*/
function getFPAddressByIndex(uint256 _index) external view returns (address) {
return FPContractsList[_index];
}
/**
* @dev get the i-th element in FPContractsList array
*/
function getFactoryContext() external view returns (address, address, uint) {
return (seedAddress, internalDEXAddress, factoryDeployBlock);
}
} | get the i-th element in every array/ | function getContractsByIndex(uint256 _index) external view returns (address, address, address, address) {
return(deployerList[_index], ATContractsList[_index], TContractsList[_index], FPContractsList[_index]);
}
| 1,070,869 |
./full_match/5/0xbC249A1D91DbD54CEEfBBdC66e01FC515FA3980c/sources/src/contracts/facilitators/aave/tokens/GhoAToken.sol | @inheritdoc IInitializableAToken | function initialize(
IPool initializingPool,
address treasury,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 aTokenDecimals,
string calldata aTokenName,
string calldata aTokenSymbol,
bytes calldata params
) external override initializer {
require(initializingPool == POOL, Errors.POOL_ADDRESSES_DO_NOT_MATCH);
_setName(aTokenName);
_setSymbol(aTokenSymbol);
_setDecimals(aTokenDecimals);
_treasury = treasury;
_underlyingAsset = underlyingAsset;
_incentivesController = incentivesController;
_domainSeparator = _calculateDomainSeparator();
emit Initialized(
underlyingAsset,
address(POOL),
treasury,
address(incentivesController),
aTokenDecimals,
aTokenName,
aTokenSymbol,
params
);
}
| 7,037,060 |
./partial_match/1/0x1c73E16b68933Ae54664B04559C030E5136F823e/sources/Ruletka.sol | Assigns a new address to act as the CTO. _newCTO The address of the new CTO | function setCTO(address payable _newCTO) public onlyCTO {
require(_newCTO != address(0));
CTO = _newCTO;
}
| 9,310,416 |
./full_match/1/0xD889E4B5301c860A27831e2eDE451A70e54BcED5/sources/contracts/EyeconsRebasePoolV1.sol | @inheritdoc IEyeconsRebasePoolV1 | function numberOfDepositedTokensByAccount(address account_) external view returns (uint256) {
return _depositedTokenIdsByAccount[account_].length();
}
| 5,006,795 |
// Sources flattened with hardhat v2.1.1 https://hardhat.org
// File contracts/Dependencies/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/**
* Based on the OpenZeppelin IER20 interface:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
*
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/**
* @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);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @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 contracts/Dependencies/IERC2612.sol
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*
* Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
*/
interface IERC2612 {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount,
uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases `owner`'s nonce by one. This
* prevents a signature from being used multiple times.
*
* `owner` can limit the time a Permit is valid for by setting `deadline` to
* a value in the near future. The deadline argument can be set to uint(-1) to
* create Permits that effectively never expire.
*/
function nonces(address owner) external view returns (uint256);
function version() external view returns (string memory);
function permitTypeHash() external view returns (bytes32);
function domainSeparator() external view returns (bytes32);
}
// File contracts/Interfaces/ILQTYToken.sol
interface ILQTYToken is IERC20, IERC2612 {
// --- Events ---
event CommunityIssuanceAddressSet(address _communityIssuanceAddress);
event LockupContractFactoryAddressSet(address _lockupContractFactoryAddress);
// --- Functions ---
function getDeploymentStartTime() external view returns (uint256);
function getLpRewardsEntitlement() external view returns (uint256);
}
// File contracts/Interfaces/ICommunityIssuance.sol
interface ICommunityIssuance {
// --- Events ---
event LQTYTokenAddressSet(address _lqtyTokenAddress);
event RewardTokenAdded(address _rewardTokenAddress, uint rewardRatio);
event RewardRatioUpdated(address _rewardTokenAddress, uint rewardRatio);
event StabilityPoolAddressSet(address _stabilityPoolAddress);
event TotalLQTYIssuedUpdated(uint _totalLQTYIssued);
// --- Functions ---
function setAddresses(address _lqtyTokenAddress, address _stabilityPoolAddress) external;
function issueLQTY() external returns (uint);
function sendLQTY(address _account, uint _LQTYamount) external;
function addRewardToken(address _rewardTokenAddress, uint rewardTokenRatio) external;
function setRewardTokenRatio(address _rewardTokenAddress, uint _rewardRatio) external;
}
// File contracts/Dependencies/BaseMath.sol
contract BaseMath {
uint constant public DECIMAL_PRECISION = 1e18;
}
// File contracts/Dependencies/SafeMath.sol
/**
* Based on OpenZeppelin's SafeMath:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
*
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File contracts/Dependencies/console.sol
// Buidler's helper contract for console logging
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function log() internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log()"));
ignored;
} function logInt(int p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(int)", p0));
ignored;
}
function logUint(uint p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0));
ignored;
}
function logString(string memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0));
ignored;
}
function logBool(bool p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0));
ignored;
}
function logAddress(address p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0));
ignored;
}
function logBytes(bytes memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes)", p0));
ignored;
}
function logByte(byte p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(byte)", p0));
ignored;
}
function logBytes1(bytes1 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes1)", p0));
ignored;
}
function logBytes2(bytes2 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes2)", p0));
ignored;
}
function logBytes3(bytes3 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes3)", p0));
ignored;
}
function logBytes4(bytes4 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes4)", p0));
ignored;
}
function logBytes5(bytes5 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes5)", p0));
ignored;
}
function logBytes6(bytes6 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes6)", p0));
ignored;
}
function logBytes7(bytes7 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes7)", p0));
ignored;
}
function logBytes8(bytes8 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes8)", p0));
ignored;
}
function logBytes9(bytes9 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes9)", p0));
ignored;
}
function logBytes10(bytes10 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes10)", p0));
ignored;
}
function logBytes11(bytes11 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes11)", p0));
ignored;
}
function logBytes12(bytes12 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes12)", p0));
ignored;
}
function logBytes13(bytes13 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes13)", p0));
ignored;
}
function logBytes14(bytes14 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes14)", p0));
ignored;
}
function logBytes15(bytes15 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes15)", p0));
ignored;
}
function logBytes16(bytes16 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes16)", p0));
ignored;
}
function logBytes17(bytes17 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes17)", p0));
ignored;
}
function logBytes18(bytes18 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes18)", p0));
ignored;
}
function logBytes19(bytes19 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes19)", p0));
ignored;
}
function logBytes20(bytes20 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes20)", p0));
ignored;
}
function logBytes21(bytes21 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes21)", p0));
ignored;
}
function logBytes22(bytes22 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes22)", p0));
ignored;
}
function logBytes23(bytes23 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes23)", p0));
ignored;
}
function logBytes24(bytes24 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes24)", p0));
ignored;
}
function logBytes25(bytes25 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes25)", p0));
ignored;
}
function logBytes26(bytes26 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes26)", p0));
ignored;
}
function logBytes27(bytes27 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes27)", p0));
ignored;
}
function logBytes28(bytes28 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes28)", p0));
ignored;
}
function logBytes29(bytes29 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes29)", p0));
ignored;
}
function logBytes30(bytes30 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes30)", p0));
ignored;
}
function logBytes31(bytes31 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes31)", p0));
ignored;
}
function logBytes32(bytes32 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes32)", p0));
ignored;
}
function log(uint p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0));
ignored;
}
function log(string memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0));
ignored;
}
function log(bool p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0));
ignored;
}
function log(address p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0));
ignored;
}
function log(uint p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint)", p0, p1));
ignored;
}
function log(uint p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string)", p0, p1));
ignored;
}
function log(uint p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool)", p0, p1));
ignored;
}
function log(uint p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address)", p0, p1));
ignored;
}
function log(string memory p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint)", p0, p1));
ignored;
}
function log(string memory p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string)", p0, p1));
ignored;
}
function log(string memory p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool)", p0, p1));
ignored;
}
function log(string memory p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address)", p0, p1));
ignored;
}
function log(bool p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint)", p0, p1));
ignored;
}
function log(bool p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string)", p0, p1));
ignored;
}
function log(bool p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool)", p0, p1));
ignored;
}
function log(bool p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address)", p0, p1));
ignored;
}
function log(address p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint)", p0, p1));
ignored;
}
function log(address p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string)", p0, p1));
ignored;
}
function log(address p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool)", p0, p1));
ignored;
}
function log(address p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address)", p0, p1));
ignored;
}
function log(uint p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
ignored;
}
}
// File contracts/Dependencies/LiquityMath.sol
library LiquityMath {
using SafeMath for uint;
uint internal constant DECIMAL_PRECISION = 1e18;
/* Precision for Nominal ICR (independent of price). Rationale for the value:
*
* - Making it “too high” could lead to overflows.
* - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.
*
* This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH,
* and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
*
*/
uint internal constant NICR_PRECISION = 1e20;
function _min(uint _a, uint _b) internal pure returns (uint) {
return (_a < _b) ? _a : _b;
}
function _max(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a : _b;
}
/*
* Multiply two decimal numbers and use normal rounding rules:
* -round product up if 19'th mantissa digit >= 5
* -round product down if 19'th mantissa digit < 5
*
* Used only inside the exponentiation, _decPow().
*/
function decMul(uint x, uint y) internal pure returns (uint decProd) {
uint prod_xy = x.mul(y);
decProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION);
}
/*
* _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
*
* Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
*
* Called by two functions that represent time in units of minutes:
* 1) TroveManager._calcDecayedBaseRate
* 2) CommunityIssuance._getCumulativeIssuanceFraction
*
* The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
* "minutes in 1000 years": 60 * 24 * 365 * 1000
*
* If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
* negligibly different from just passing the cap, since:
*
* In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
* In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
*/
function _decPow(uint _base, uint _minutes) internal pure returns (uint) {
if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow
if (_minutes == 0) {return DECIMAL_PRECISION;}
uint y = DECIMAL_PRECISION;
uint x = _base;
uint n = _minutes;
// Exponentiation-by-squaring
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n.div(2);
} else { // if (n % 2 != 0)
y = decMul(x, y);
x = decMul(x, x);
n = (n.sub(1)).div(2);
}
}
return decMul(x, y);
}
function _getAbsoluteDifference(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a.sub(_b) : _b.sub(_a);
}
function _computeNominalCR(uint _coll, uint _debt, uint _collDecimalAdjustment) internal pure returns (uint) {
if (_debt > 0) {
return _coll.mul(_collDecimalAdjustment).mul(NICR_PRECISION).div(_debt);
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
function _computeCR(uint _coll, uint _debt, uint _price, uint _collDecimalAdjustment) internal pure returns (uint) {
if (_debt > 0) {
uint newCollRatio = _coll.mul(_collDecimalAdjustment).mul(_price).div(_debt);
return newCollRatio;
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
}
// File contracts/Dependencies/Ownable.sol
/**
* Based on OpenZeppelin's Ownable contract:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*
* NOTE: This function is not safe, as it doesn’t check owner is calling it.
* Make sure you check it before calling it.
*/
function _renounceOwnership() internal {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
// File contracts/Dependencies/CheckContract.sol
contract CheckContract {
/**
* Check that the account is an already deployed non-destroyed contract.
* See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L12
*/
function checkContract(address _account) internal view {
require(_account != address(0), "Account cannot be zero address");
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_account) }
require(size > 0, "Account code size cannot be zero");
}
}
// File contracts/LQTY/CommunityIssuance.sol
contract CommunityIssuance is ICommunityIssuance, Ownable, CheckContract, BaseMath {
using SafeMath for uint;
// --- Data ---
string constant public NAME = "CommunityIssuance";
uint constant public SECONDS_IN_ONE_MINUTE = 60;
uint constant public MINUTES_IN_ONE_YEAR = 60 * 24 * 365;
ILQTYToken public lqtyToken;
mapping (address => bool) public rewardTokens;
address[] public rewardTokenList;
address public stabilityPoolAddress;
uint public totalLQTYIssued;
mapping (address => uint) public rewardTokenRatio;
uint public lastIssueTime; // last issue time
uint public issuanceFactor; // issue amount per minute
uint public lastUnIssued; // UnIssused amount since last issuance update
uint public immutable deploymentTime;
// --- Events ---
event LQTYTokenAddressSet(address _lqtyTokenAddress);
event RewardTokenAdded(address _rewardTokenAddress, uint rewardRatio);
event RewardRatioUpdated(address _rewardTokenAddress, uint rewardRatio);
event StabilityPoolAddressSet(address _stabilityPoolAddress);
event TotalLQTYIssuedUpdated(uint _totalLQTYIssued);
enum Functions {
SET_ADDRESS,
ADD_REWARD_TOKEN,
SET_ISSUANCE_FACTOR,
SET_REWARD_TOKEN_RATIO
}
uint private constant _TIMELOCK = 1 days;
mapping(Functions => uint) public timelock;
// --- Time lock
modifier notLocked(Functions _fn) {
require(timelock[_fn] != 1 && timelock[_fn] <= block.timestamp, "Function is timelocked");
_;
}
//unlock timelock
function unlockFunction(Functions _fn) public onlyOwner {
timelock[_fn] = block.timestamp + _TIMELOCK;
}
//lock timelock
function lockFunction(Functions _fn) public onlyOwner {
timelock[_fn] = 1;
}
// --- Functions ---
constructor() public {
uint syncTime = block.timestamp;
deploymentTime = syncTime;
lastIssueTime = syncTime;
}
function setAddresses
(
address _lqtyTokenAddress,
address _stabilityPoolAddress
)
external
onlyOwner
override
notLocked(Functions.SET_ADDRESS)
{
checkContract(_lqtyTokenAddress);
checkContract(_stabilityPoolAddress);
lqtyToken = ILQTYToken(_lqtyTokenAddress);
stabilityPoolAddress = _stabilityPoolAddress;
checkContract(_stabilityPoolAddress);
// When LQTYToken deployed, it should have transferred CommunityIssuance's LQTY entitlement
uint LQTYBalance = lqtyToken.balanceOf(address(this));
//set default ISSUANCE_FACTOR for one year
issuanceFactor = LQTYBalance.div(MINUTES_IN_ONE_YEAR);
emit LQTYTokenAddressSet(_lqtyTokenAddress);
emit StabilityPoolAddressSet(_stabilityPoolAddress);
timelock[Functions.SET_ADDRESS] = 1;
}
function setIssuanceFactor(uint _issuanceFactor) external onlyOwner notLocked(Functions.SET_ISSUANCE_FACTOR) {
require(_issuanceFactor > 0, "CommunityIssuance: Issuance Factor cannot be zero");
issuanceFactor = _issuanceFactor;
timelock[Functions.SET_ISSUANCE_FACTOR] = 1;
}
function addRewardToken
(
address _rewardTokenAddress,
uint _rewardRatio
)
external
onlyOwner
override
notLocked(Functions.ADD_REWARD_TOKEN)
{
require(!rewardTokens[_rewardTokenAddress], "CommunityIssuance: rewardTokenAddress already exists");
require(_rewardRatio > 0, "CommunityIssuance: rewardRatio cannot be zero");
checkContract(_rewardTokenAddress);
rewardTokens[_rewardTokenAddress] = true;
rewardTokenRatio[_rewardTokenAddress] = _rewardRatio;
rewardTokenList.push(_rewardTokenAddress);
emit RewardTokenAdded(_rewardTokenAddress, _rewardRatio);
timelock[Functions.ADD_REWARD_TOKEN] = 1;
}
function setRewardTokenRatio
(
address _rewardTokenAddress,
uint _rewardRatio
)
external
onlyOwner
override
notLocked(Functions.SET_REWARD_TOKEN_RATIO)
{
require(rewardTokens[_rewardTokenAddress], "CommunityIssuance: rewardTokenAddress does not exist");
require(_rewardRatio >= 0, "CommunityIssuance: rewardRatio must be at least zero");
rewardTokenRatio[_rewardTokenAddress] = _rewardRatio;
emit RewardRatioUpdated(_rewardTokenAddress, _rewardRatio);
timelock[Functions.SET_REWARD_TOKEN_RATIO] = 1;
}
function issueLQTY() external override returns (uint) {
_requireCallerIsStabilityPool();
uint issuance = _getCumulativeIssuanceAmount().add(lastUnIssued);
uint LQTYBalance = lqtyToken.balanceOf(address(this));
uint issuable = 0;
if (LQTYBalance > issuance) {
issuable = issuance;
} else {
issuable = LQTYBalance;
}
totalLQTYIssued = totalLQTYIssued.add(issuable);
lastIssueTime = block.timestamp;
lastUnIssued = issuance.sub(issuable);
emit TotalLQTYIssuedUpdated(issuable);
return issuable;
}
function _getCumulativeIssuanceAmount() internal view returns (uint) {
uint timePassedInMinutes = block.timestamp.sub(lastIssueTime).div(SECONDS_IN_ONE_MINUTE);
uint cumulativeIssuanceAmount = issuanceFactor.mul(timePassedInMinutes);
return cumulativeIssuanceAmount;
}
function sendLQTY(address _account, uint _LQTYamount) external override {
_requireCallerIsStabilityPool();
lqtyToken.transfer(_account, _LQTYamount);
// Transfer additional rewards
for (uint i = 0; i < rewardTokenList.length; i++) {
IERC20(rewardTokenList[i]).transfer(_account, _LQTYamount.div(DECIMAL_PRECISION).mul(rewardTokenRatio[rewardTokenList[i]]));
}
}
// --- 'require' functions ---
function _requireCallerIsStabilityPool() internal view {
require(msg.sender == stabilityPoolAddress, "CommunityIssuance: caller is not SP");
}
} | --- Events --- --- Functions --- | interface ILQTYToken is IERC20, IERC2612 {
event CommunityIssuanceAddressSet(address _communityIssuanceAddress);
event LockupContractFactoryAddressSet(address _lockupContractFactoryAddress);
function getDeploymentStartTime() external view returns (uint256);
function getLpRewardsEntitlement() external view returns (uint256);
}
}
| 1,478,199 |
./partial_match/1/0xD3111A14E8df0Df749CF881AE414037D732D8d28/sources/ComboOracle_KyberSwapElasticV2.sol | Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./ | interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
pragma solidity >=0.8.0;
}
| 2,731,251 |
pragma solidity ^0.4.18;
contract Lotto {
address public owner = msg.sender;
address[] internal playerPool;
uint seed = 0;
uint amount = 0.1 ether;
// events
event Payout(address from, address to, uint quantity);
event BoughtIn(address from);
event Rejected();
modifier onlyBy(address _account) {
require(msg.sender == _account);
_;
}
function changeOwner(address _newOwner) public onlyBy(owner) {
owner = _newOwner;
}
/*
The reasoning behind this method to get a random number is, because I'm not
displaying the current number of players, no one should know who the 11th player
will be, and that should be random enough to prevent anyone from cheating the system.
The reward is only 1 ether so it's low enough that miners won't try to influence it
... i hope.
*/
function random(uint upper) internal returns (uint) {
seed = uint(keccak256(keccak256(playerPool[playerPool.length -1], seed), now));
return seed % upper;
}
// only accepts a value of 0.01 ether. no extra eth please!! don't be crazy!
// i'll make contracts for different sized bets eventually.
function buyIn() payable public returns (uint) {
if (msg.value * 10 != 0.1 ether) {
revert();
Rejected();
} else {
playerPool.push(msg.sender);
BoughtIn(msg.sender);
if (playerPool.length >= 11) {
selectWinner();
}
}
return playerPool.length;
}
function selectWinner() private {
address winner = playerPool[random(playerPool.length)];
winner.transfer(amount);
playerPool.length = 0;
owner.transfer(this.balance);
Payout(this, winner, amount);
}
/*
If the contract becomes stagnant and new players haven't signed up for awhile,
this function will return the money to all the players. The function is made
payable so I can send some ether with the transaction to pay for gas. this way
I can make sure all players are paid back.
as a note, 100 finney == 0.1 ether.
*/
function refund() public onlyBy(owner) payable {
require(playerPool.length > 0);
for (uint i = 0; i < playerPool.length; i++) {
playerPool[i].transfer(100 finney);
}
playerPool.length = 0;
}
/*
Self destruct just in case. Also, will refund all ether to the players before it
explodes into beautiful digital star dust.
*/
function close() public onlyBy(owner) {
refund();
selfdestruct(owner);
}
// fallback function acts the same as buyIn(), omitting the return of course.
function () public payable {
require(msg.value * 10 == 0.1 ether);
playerPool.push(msg.sender);
BoughtIn(msg.sender);
if (playerPool.length >= 11) {
selectWinner();
}
}
} | fallback function acts the same as buyIn(), omitting the return of course. | function () public payable {
require(msg.value * 10 == 0.1 ether);
playerPool.push(msg.sender);
BoughtIn(msg.sender);
if (playerPool.length >= 11) {
selectWinner();
}
}
| 10,602,319 |
// SPDX-License-Identifier: MIT
// https://kanon.art - K21
// https://daemonica.io
//
//
// [email protected]@@@@@@@@@@$$$
// [email protected]@@@@@$$$$$$$$$$$$$$##
// $$$$$$$$$$$$$$$$$#########***
// $$$$$$$$$$$$$$$#######**!!!!!!
// ##$$$$$$$$$$$$#######****!!!!=========
// ##$$$$$$$$$#$#######*#***!!!=!===;;;;;
// *#################*#***!*!!======;;;:::
// ################********!!!!====;;;:::~~~~~
// **###########******!!!!!!==;;;;::~~~--,,,-~
// ***########*#*******!*!!!!====;;;::::~~-,,......,-
// ******#**********!*!!!!=!===;;::~~~-,........
// ***************!*!!!!====;;:::~~-,,..........
// !************!!!!!!===;;::~~--,............
// !!!*****!!*!!!!!===;;:::~~--,,..........
// =!!!!!!!!!=!==;;;::~~-,,...........
// =!!!!!!!!!====;;;;:::~~--,........
// ==!!!!!!=!==;=;;:::~~--,...:~~--,,,..
// ===!!!!!=====;;;;;:::~~~--,,..#*=;;:::~--,.
// ;=============;;;;;;::::~~~-,,...$$###==;;:~--.
// :;;==========;;;;;;::::~~~--,,[email protected]@$$##*!=;:~-.
// :;;;;;===;;;;;;;::::~~~--,,...$$$$#*!!=;~-
// :;;;;;;;;;;:::::~~~~---,,...!*##**!==;~,
// :::;:;;;;:::~~~~---,,,...~;=!!!!=;;:~.
// ~:::::::::::::~~~~~---,,,....-:;;=;;;~,
// ~~::::::::~~~~~~~-----,,,......,~~::::~-.
// -~~~~~~~~~~~~~-----------,,,.......,-~~~~~,.
// ---~~~-----,,,,,........,---,.
// ,,--------,,,,,,.........
// .,,,,,,,,,,,,......
// ...............
// .........
pragma solidity ^0.8.0;
/** @title Daemonica helper functions
* @author @0xAnimist
* @notice Misc support for Daemonica contract suite
*/
library Helpers{
/** @notice Converts boolean to a string
* @param value The boolean value
* @return A string that reads "true" or "false"
*/
function boolToString(bool value) public pure returns (string memory) {
if(value){
return "true";
}else{
return "false";
}
}
/** @notice Converts uint256 to a string
* @param value The uint256 value
* @return A string that represents the numerical value of the input
*/
function toString(uint256 value) public pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/** @notice Converts uint8 to a string
* @param value The uint8 value
* @return A string that represents the numerical value of the input
*/
function toString8(uint8 value) public pure returns (string memory) {
if (value == 0) {
return "00";
}
uint8 temp = value;
uint8 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer;
if(digits == 1){
buffer = new bytes(2);
buffer[0] = bytes1(uint8(48));
buffer[1] = bytes1(uint8(48 + uint8(value % 10)));
}else{
buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint8(value % 10)));
value /= 10;
}
}
return string(buffer);
}
/** @notice Returns a _delimiter delimited string of all the values in an 8 uint8 long array
* @param _array Array of uint8 values to concatenate
* @param _delimiter String to delimit each value
* @return Concatenated string of all the values delimited by _delimiter
*/
function stringifyRow(uint8[8] memory _array, string memory _delimiter) internal pure returns (string memory) {
string memory output = string(abi.encodePacked(
'<tspan x="153">',toString8(_array[0]),'</tspan>',_delimiter,
'<tspan x="198">',toString8(_array[1]),'</tspan>',_delimiter,
'<tspan x="243">',toString8(_array[2]),'</tspan>',_delimiter
));
output = string(abi.encodePacked(
output,
'<tspan x="288">',toString8(_array[3]),'</tspan>',_delimiter,
'<tspan x="333">',toString8(_array[4]),'</tspan>',_delimiter,
'<tspan x="378">',toString8(_array[5]),'</tspan>',_delimiter
));
return string(abi.encodePacked(
output,
'<tspan x="423">',toString8(_array[6]),'</tspan>',_delimiter,
'<tspan x="468">',toString8(_array[7]),'</tspan>',_delimiter
));
}
/** @notice Compares two strings
* @param _a First string to compare
* @param _b Second string to compare
* @return True if equal, false if not
*/
function compareStrings(string memory _a, string memory _b) public pure returns (bool) {
return (keccak256(abi.encodePacked((_a))) == keccak256(abi.encodePacked((_b))));
}
/** @notice Returns a substring of the given string
* @param str The string
* @param startIndex Starting index determining the substring to return
* @param endIndex Ending index determining the substring to return
* @return Substring parsed from the string
*/
function substring(string memory str, uint startIndex, uint endIndex) public pure returns (string memory) {
bytes memory strBytes = bytes(str);
if(endIndex == 0){
endIndex = strBytes.length;
}
bytes memory result = new bytes(endIndex-startIndex);
for(uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
/** @notice Returns a pseudorandom number from a string input
* @param input A string to seed the pseudorandom number generator
* @return A pseudorandom uint256 number based on the input string
*/
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
} | Compares two strings _a First string to compare _b Second string to compare return True if equal, false if not/ | function compareStrings(string memory _a, string memory _b) public pure returns (bool) {
return (keccak256(abi.encodePacked((_a))) == keccak256(abi.encodePacked((_b))));
}
| 15,366,490 |
./partial_match/97/0xbc877c0f73520f80fFAEc815C6edeD1BB28b4eba/sources/RubinToken.sol | Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance | function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "RUBIN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 11,356,692 |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => uint256) private authorizedContracts;
uint8 private constant PAYOUT_PERCENTAGE = 150;
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
struct Airline {
bool isRegistered;
bool isFunded;
uint256 funds;
}
mapping(address => Airline) private registeredAirlines; // track registered airlines, for multi-sig and airline ante
uint256 public totalRegisteredAirlines = 0;
// Insurance from passengers
struct Insurance {
address passenger;
uint256 insuranceCost;
uint256 payoutPercentage;
bool isPayoutCredited;
}
// mapping(bytes32 => Insurance[]) public flightKeyInsurance;
mapping(bytes32 => Insurance) public passengerInsurance; // (encoded passenger+flightKey => Insurance)
mapping(address => uint256) public passengerCredits; // passenger => insurance payouts in eth, pending withdrawal
struct Flight {
address airline;
uint8 statusCode;
uint256 timestamp;
string flightNo;
string departureFrom;
string arrivalAt;
bool isRegistered;
address[] insurees;
}
mapping(bytes32 => Flight) public flights; // key => Flight
uint256 public totalRegisteredFlights = 0;
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(address airlineAddress) public {
contractOwner = msg.sender;
registeredAirlines[airlineAddress] = Airline(true, false, 0); // initialise and register first airline
++totalRegisteredAirlines;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the function caller to be an authorized account
*/
modifier requireIsCallerAuthorized() {
require(
authorizedContracts[msg.sender] == 1,
"Caller is not authorized"
);
_;
}
/**
* @dev Modifier that requires the airline to be registered (may not be funded yet)
*/
modifier requireAirlineIsRegistered(address airlineAddress) {
require(
registeredAirlines[airlineAddress].isRegistered == true,
"Caller is not a registered airline"
);
_;
}
/**
* @dev Modifier that requires the ariline to be funded
*/
modifier requireAirlineIsFunded(address airlineAddress) {
require(
registeredAirlines[airlineAddress].isFunded == true,
"Caller's account is not funded yet"
);
_;
}
/**
* @dev Modifier that requires the flight to be registered
*/
modifier requireRegisteredFlight(bytes32 key) {
require(
flights[key].isRegistered == true,
"Flight is not registered yet"
);
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns (bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) public requireContractOwner {
operational = mode;
}
/**
* @dev Authorize a contract address (FlightSuretyApp contract)
*/
function authorizeContract(address contractAddress)
public
requireContractOwner
{
authorizedContracts[contractAddress] = 1;
}
/**
* @dev Deauthorize a contract address (FlightSuretyApp contract)
*/
function deauthorizeContract(address contractAddress)
public
requireContractOwner
{
delete authorizedContracts[contractAddress];
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/* AIRLINE FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
* Only funded airlines can be
*/
function registerAirline(address newAirlineAddress)
external
requireIsOperational
requireIsCallerAuthorized
{
// Check that airline is not already registered
require(
!registeredAirlines[newAirlineAddress].isRegistered,
"Airline is already registered"
);
registeredAirlines[newAirlineAddress] = Airline({
isRegistered: true,
isFunded: false,
funds: 0
});
++totalRegisteredAirlines;
}
/**
* @dev Check an airline's registration status
*
*/
function isRegisteredAirline(address airlineAddress)
external
view
requireIsOperational
returns (bool)
{
return registeredAirlines[airlineAddress].isRegistered;
}
/**
* @dev Check an airline's funding status
*
*/
function isFundedAirline(address airlineAddress)
external
view
requireIsOperational
returns (bool)
{
return registeredAirlines[airlineAddress].isFunded;
}
/**
* @dev Check an airline's funding amount
*
*/
function getFundsForAirline(address airlineAddress)
external
view
requireIsOperational
returns (uint256)
{
return registeredAirlines[airlineAddress].funds;
}
/**
* @dev Get total number of registered airlines
*
*/
function getTotalRegisteredAirlines()
external
view
requireIsOperational
returns (uint256)
{
return totalRegisteredAirlines;
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(address airlineAddress, uint256 amount)
external
payable
requireIsOperational
returns (bool)
{
require(
registeredAirlines[airlineAddress].isRegistered,
"Airline is not registered yet"
);
registeredAirlines[airlineAddress].isFunded = true;
registeredAirlines[airlineAddress].funds += amount;
return registeredAirlines[airlineAddress].isFunded;
}
/* PASSENGER FUNCTIONS */
/********************************************************************************************/
/**
* @dev Buy insurance for a flight
*
*/
function buy(
address passenger,
address airline,
string flightNo,
uint256 timestamp,
uint256 cost
) external payable requireIsOperational {
bytes32 key = getFlightKey(airline, flightNo, timestamp);
bytes32 insuranceKey = keccak256(abi.encodePacked(passenger, key));
passengerInsurance[insuranceKey] = Insurance({
passenger: passenger,
insuranceCost: cost,
payoutPercentage: PAYOUT_PERCENTAGE,
isPayoutCredited: false
});
flights[key].insurees.push(passenger);
}
function isPassengerInsured(
address passenger,
address airline,
string flightNo,
uint256 timestamp
) external view requireIsOperational returns (bool) {
bytes32 key = getFlightKey(airline, flightNo, timestamp);
bytes32 insuranceKey = keccak256(abi.encodePacked(passenger, key));
return passengerInsurance[insuranceKey].passenger == passenger;
}
/**
* @dev Credits payouts to insuree
*/
function creditInsuree(address passenger, bytes32 key)
internal
requireIsOperational
{
bytes32 insuranceKey = keccak256(abi.encodePacked(passenger, key));
require(
passengerInsurance[insuranceKey].passenger == passenger,
"Passenger does not own insurance for this flight"
);
require(
!passengerInsurance[insuranceKey].isPayoutCredited,
"Passenger has already been credited"
);
// calculate payout
uint256 amount = passengerInsurance[insuranceKey]
.insuranceCost
.mul(passengerInsurance[insuranceKey].payoutPercentage)
.div(100);
passengerInsurance[insuranceKey].isPayoutCredited = true;
passengerCredits[passenger] += amount;
}
function getPassengerCredits(address passenger)
external
view
returns (uint256)
{
return passengerCredits[passenger];
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address passenger) external payable requireIsOperational {
require(
passengerCredits[passenger] > 0,
"Passenger does not have credits to withdraw"
);
uint256 credits = passengerCredits[passenger];
passengerCredits[passenger] = 0;
passenger.transfer(credits);
}
/* FLIGHT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Register a new flight
*
*/
function registerFlight(
address airline,
string flightNo,
string departureFrom,
string arrivalAt,
uint256 timestamp
)
external
requireIsOperational
requireAirlineIsRegistered(airline)
requireAirlineIsFunded(airline)
returns (bytes32, bool)
{
require(
!flights[key].isRegistered,
"Flight has already been registered"
);
bytes32 key = getFlightKey(airline, flightNo, timestamp);
// Flight memory newFlight
flights[key] = Flight({
airline: airline,
statusCode: STATUS_CODE_UNKNOWN,
timestamp: timestamp,
flightNo: flightNo,
departureFrom: departureFrom,
arrivalAt: arrivalAt,
isRegistered: true,
insurees: new address[](0)
});
++totalRegisteredFlights;
return (key, flights[key].isRegistered);
}
function isRegisteredFlight(
address airline,
string flightNo,
uint256 timestamp
) external view requireIsOperational returns (bool) {
bytes32 key = getFlightKey(airline, flightNo, timestamp);
return flights[key].isRegistered;
}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Save flight status info
*
*/
function processFlightStatus(
address airline,
string flightNo,
uint256 timestamp,
uint8 statusCode
) external requireIsOperational {
bytes32 key = getFlightKey(airline, flightNo, timestamp);
if (flights[key].statusCode == STATUS_CODE_UNKNOWN) {
flights[key].statusCode = statusCode;
if (statusCode == STATUS_CODE_LATE_AIRLINE) {
// airline is late, credit insured amount to passengers
uint256 numInsurees = flights[key].insurees.length;
for (uint256 i = 0; i < numInsurees; i++) {
creditInsuree(flights[key].insurees[i], key);
}
}
}
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {}
}
| Sets contract operations on/off When operational mode is disabled, all write transactions except for this one will fail/ | function setOperatingStatus(bool mode) public requireContractOwner {
operational = mode;
}
| 7,241,055 |
pragma solidity ^0.4.24;
import './SafeMath.sol';
/** @title CryptoFundFactory dApp */
contract CryptoFundFactory { // Declaration of Crypto Fund Factory Contract
constructor() public {
factoryOwner = msg.sender; // Sets the deploying developer as contract owner
}
using SafeMath for uint256; // SafeMath library prevents overflow when working with uint
address factoryOwner;
bool isStopped = false;
uint public fundCount;
uint defaultOpenFee = 0.5;
uint defaultCloseFee = 0.1;
enum FoundState {Open, Closed}
struct Allocation {
string ticker;
uint amount;
}
struct Fund {
address funderAccount;
uint seedAmount;
uint openDateUnixTimestamp;
uint closeDateUnixTimestamp;
Allocation openAllocation [];
Allocation closeAllocation [];
FundState fundState;
}
mapping(uint => Fund) public FundList;
// event AcceptSubmission (uint bountyId, uint submissionId);
modifier verifyBountyOwner (uint _bountyId) {
require (msg.sender == BountyList[_bountyId].bountyPoster); _;
}
//FRONT END:
// wait/ timeout for funding
// wait for confirmations
// FRONT END CALLS FACTORY:
// 1 Generate new address & send transaction to initiate new FundContract
/** @dev Creates a new BountyItem to which users can submit HunterSubmission solutions.
* @param _title Title of a new BountyItem.
* @return boolean Returns true if function is executes successfully.
*/
function updateFundOwner() public returns (bool) {
}
//FRONT END:
// set fund open date
// set fund allocation
// set seedFunder
//FRONT END CALLS FACTORY:
// send seed funds to new FoundAccount
/** @dev Creates a new BountyItem to which users can submit HunterSubmission solutions.
* @param _title Title of a new BountyItem.
* @return boolean Returns true if function is executes successfully.
*/
function updateFundOwner() public returns (bool) {
}
/// @dev Fallback function, which accepts ether when sent to contract.
function() public payable {}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////
// child / FundAccount
// set openAllocation
// set seedFunder
// accept funding
// close/liquidate
// - send split to partentseed funder (minus fees) * fund title
// - update parent data?
contract CryptoFund { // Declaration of Crypto Fund Factory Contract
constructor() public {
parentContract = msg.sender;
// openDateUnixTimestamp = openDateUnixTimes - how?
}
using SafeMath for uint256; // SafeMath library prevents overflow when working with uint
string title;
address parentContract;
address fundOwner; // Specifies the owner address of the contract
uint seedAmount; // Reward Amount for submitting an accepted HunterSubmission.
uint openDateUnixTimestamp
uint closeDateUnixTimestamp
Allocation openAllocation []
Allocation closeAllocation []
uint openFee;
uint closeFee;
FoundState fundState;
enum FoundState {Open, Closed} // Current state of a BountyItem.
struct Allocation { // Declaration of HunterSubmission struct type
string ticker; // Solution body of text.
uint amount; // Address of a Bounty Hunter.
}
/** @dev Creates a new BountyItem to which users can submit HunterSubmission solutions.
* @param _title Title of a new BountyItem.
* @param _description Description of a new BountyItem.
* @param _bountyAmount Bounty award amount for a new BountyItem.
* @return boolean Returns true if function is executes successfully.
*/
function acceptInitialAllocation(string _title, string _description, uint _bountyAmount) public payable stoppedInEmergency() returns (bool) {
bountyCount++;
var newBountyItem = BountyItem(msg.sender, _title, _description, _bountyAmount, BountyState.Open, 0);
BountyList[bountyCount] = newBountyItem;
emit CreateBounty(bountyCount, msg.sender, _title, _description, _bountyAmount, BountyState.Open, 0);
return true;
}
/** @dev Creates a new BountyItem to which users can submit HunterSubmission solutions.
* @param _title Title of a new BountyItem.
* @return boolean Returns true if function is executes successfully.
*/
function updateFundOwner() public returns (bool) {
}
/** @dev Creates a new BountyItem to which users can submit HunterSubmission solutions.
* @param _title Title of a new BountyItem.
* @return boolean Returns true if function is executes successfully.
*/
function updateFundOwner() public returns (bool) {
}
/** @dev Creates a new BountyItem to which users can submit HunterSubmission solutions.
* @param _title Title of a new BountyItem.
* @return boolean Returns true if function is executes successfully.
*/
function liquidateFund() public returns (bool) {
//send fundOwner holdings - fees
// send contractFactory remaining holdings
// update parentData?
}
/// @dev Fallback function, which accepts ether when sent to contract.
function() public payable {}
}
| FRONT END CALLS FACTORY: send seed funds to new FoundAccount Creates a new BountyItem to which users can submit HunterSubmission solutions. _title Title of a new BountyItem. return boolean Returns true if function is executes successfully./ | function updateFundOwner() public returns (bool) {
}
| 12,941,142 |
// SPDX-License-Identifier: BSD-2-Clause
// CompoundModule.sol
// Copyright (c) 2021 Giry SAS. All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 2. 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.8.10;
pragma abicoder v2;
import "../interfaces/compound/ICompound.sol";
import "../lib/Exponential.sol";
import {MgvLib as ML} from "../../MgvLib.sol";
//import "hardhat/console.sol";
contract CompoundModule is Exponential {
event ErrorOnRedeem(
address indexed outbound_tkn,
address indexed inbound_tkn,
uint indexed offerId,
uint amount,
uint errorCode
);
event ErrorOnMint(
address indexed outbound_tkn,
address indexed inbound_tkn,
uint indexed offerId,
uint amount,
uint errorCode
);
event ComptrollerError(address comp, uint errorCode);
// mapping : ERC20 -> cERC20
mapping(IERC20 => IcERC20) overlyings;
// address of the comptroller
IComptroller public immutable comptroller;
// address of the price oracle used by the comptroller
ICompoundPriceOracle public immutable oracle;
IERC20 immutable weth;
constructor(address _unitroller, address wethAddress) {
comptroller = IComptroller(_unitroller); // unitroller is a proxy for comptroller calls
require(_unitroller != address(0), "Invalid comptroller address");
ICompoundPriceOracle _oracle = IComptroller(_unitroller).oracle(); // pricefeed used by the comptroller
require(address(_oracle) != address(0), "Failed to get price oracle");
oracle = _oracle;
weth = IERC20(wethAddress);
}
function isCeth(IcERC20 ctoken) internal view returns (bool) {
return (keccak256(abi.encodePacked(ctoken.symbol())) ==
keccak256(abi.encodePacked("cETH")));
}
//dealing with cEth special case
function underlying(IcERC20 ctoken) internal view returns (IERC20) {
require(ctoken.isCToken(), "Invalid ctoken address");
if (isCeth(ctoken)) {
// cETH has no underlying() function...
return weth;
} else {
return IERC20(ctoken.underlying());
}
}
function _approveLender(IcERC20 ctoken, uint amount) internal returns (bool) {
IERC20 token = underlying(ctoken);
return token.approve(address(ctoken), amount);
}
function _enterMarkets(address[] calldata ctokens) internal {
uint[] memory results = comptroller.enterMarkets(ctokens);
for (uint i = 0; i < ctokens.length; i++) {
require(results[i] == 0, "Failed to enter market");
IERC20 token = underlying(IcERC20(ctokens[i]));
// adding ctoken.underlying --> ctoken mapping
overlyings[token] = IcERC20(ctokens[i]);
}
}
function _exitMarket(IcERC20 ctoken) internal {
require(
comptroller.exitMarket(address(ctoken)) == 0,
"failed to exit marker"
);
}
function _claimComp() internal {
comptroller.claimComp(address(this));
}
function isPooled(IERC20 token) public view returns (bool) {
IcERC20 ctoken = overlyings[token];
return comptroller.checkMembership(address(this), ctoken);
}
/// @notice struct to circumvent stack too deep error in `maxGettableUnderlying` function
struct Heap {
uint ctokenBalance;
uint cDecimals;
uint decimals;
uint exchangeRateMantissa;
uint liquidity;
uint collateralFactorMantissa;
uint maxRedeemable;
uint balanceOfUnderlying;
uint priceMantissa;
uint underlyingLiquidity;
MathError mErr;
uint errCode;
}
function heapError(Heap memory heap) private pure returns (bool) {
return (heap.errCode != 0 || heap.mErr != MathError.NO_ERROR);
}
/// @notice Computes maximal maximal redeem capacity (R) and max borrow capacity (B|R) after R has been redeemed
/// returns (R, B|R)
function maxGettableUnderlying(address _ctoken, address account)
public
view
returns (uint, uint)
{
IcERC20 ctoken = IcERC20(_ctoken);
Heap memory heap;
// NB balance below is underestimated unless accrue interest was triggered earlier in the transaction
(heap.errCode, heap.ctokenBalance, , heap.exchangeRateMantissa) = ctoken
.getAccountSnapshot(address(this)); // underapprox
heap.priceMantissa = oracle.getUnderlyingPrice(ctoken); //18 decimals
// balanceOfUnderlying(A) : cA.balance * exchange_rate(cA,A)
(heap.mErr, heap.balanceOfUnderlying) = mulScalarTruncate(
Exp({mantissa: heap.exchangeRateMantissa}),
heap.ctokenBalance // ctokens have 8 decimals precision
);
if (heapError(heap)) {
return (0, 0);
}
// max amount of outbound_Tkn token than can be borrowed
(
heap.errCode,
heap.liquidity, // is USD:18 decimals
/*shortFall*/
) = comptroller.getAccountLiquidity(account); // underapprox
// to get liquidity expressed in outbound_Tkn token instead of USD
(heap.mErr, heap.underlyingLiquidity) = divScalarByExpTruncate(
heap.liquidity,
Exp({mantissa: heap.priceMantissa})
);
if (heapError(heap)) {
return (0, 0);
}
(, heap.collateralFactorMantissa, ) = comptroller.markets(address(ctoken));
// if collateral factor is 0 then any token can be redeemed from the pool w/o impacting borrow power
// also true if market is not entered
if (
heap.collateralFactorMantissa == 0 ||
!comptroller.checkMembership(account, ctoken)
) {
return (heap.balanceOfUnderlying, heap.underlyingLiquidity);
}
// maxRedeem:[underlying] = liquidity:[USD / 18 decimals ] / (price(outbound_tkn):[USD.underlying^-1 / 18 decimals] * collateralFactor(outbound_tkn): [0-1] 18 decimals)
(heap.mErr, heap.maxRedeemable) = divScalarByExpTruncate(
heap.liquidity,
mul_(
Exp({mantissa: heap.collateralFactorMantissa}),
Exp({mantissa: heap.priceMantissa})
)
);
if (heapError(heap)) {
return (0, 0);
}
heap.maxRedeemable = min(heap.maxRedeemable, heap.balanceOfUnderlying);
// B|R = B - R*CF
return (
heap.maxRedeemable,
sub_(
heap.underlyingLiquidity, //borrow power
mul_ScalarTruncate(
Exp({mantissa: heap.collateralFactorMantissa}),
heap.maxRedeemable
)
)
);
}
function compoundRedeem(uint amountToRedeem, ML.SingleOrder calldata order)
internal
returns (uint)
{
IcERC20 outbound_cTkn = overlyings[IERC20(order.outbound_tkn)]; // this is 0x0 if outbound_tkn is not compound sourced.
if (address(outbound_cTkn) == address(0)) {
return amountToRedeem;
}
uint errorCode = outbound_cTkn.redeemUnderlying(amountToRedeem); // accrues interests
if (errorCode == 0) {
//compound redeem was a success
// if ETH was redeemed, one needs to convert them into wETH
if (isCeth(outbound_cTkn)) {
weth.deposit{value: amountToRedeem}();
}
return 0;
} else {
//compound redeem failed
emit ErrorOnRedeem(
order.outbound_tkn,
order.inbound_tkn,
order.offerId,
amountToRedeem,
errorCode
);
return amountToRedeem;
}
}
function _mint(uint amount, IcERC20 ctoken) internal returns (uint errCode) {
if (isCeth(ctoken)) {
// turning `amount` of wETH into ETH
try weth.withdraw(amount) {
// minting amount of ETH into cETH
ctoken.mint{value: amount}();
} catch {
if (amount == weth.balanceOf(address(this))) {}
require(false);
}
} else {
// Approve transfer on the ERC20 contract (not needed if cERC20 is already approved for `this`)
// IERC20(ctoken.underlying()).approve(ctoken, amount);
errCode = ctoken.mint(amount); // accrues interest
}
}
// adapted from https://medium.com/compound-finance/supplying-assets-to-the-compound-protocol-ec2cf5df5aa#afff
// utility to supply erc20 to compound
function compoundMint(uint amount, ML.SingleOrder calldata order)
internal
returns (uint missing)
{
IcERC20 ctoken = overlyings[IERC20(order.inbound_tkn)];
uint errCode = _mint(amount, ctoken);
// Mint ctokens
if (errCode != 0) {
emit ErrorOnMint(
order.outbound_tkn,
order.inbound_tkn,
order.offerId,
amount,
errCode
);
missing = amount;
}
}
}
| Computes maximal maximal redeem capacity (R) and max borrow capacity (B|R) after R has been redeemed returns (R, B|R) NB balance below is underestimated unless accrue interest was triggered earlier in the transaction balanceOfUnderlying(A) : cA.balance exchange_rate(cA,A) | function maxGettableUnderlying(address _ctoken, address account)
public
view
returns (uint, uint)
{
IcERC20 ctoken = IcERC20(_ctoken);
Heap memory heap;
(heap.errCode, heap.ctokenBalance, , heap.exchangeRateMantissa) = ctoken
(heap.mErr, heap.balanceOfUnderlying) = mulScalarTruncate(
);
if (heapError(heap)) {
return (0, 0);
}
heap.errCode,
heap.liquidity,
);
if (heapError(heap)) {
return (0, 0);
}
(, heap.collateralFactorMantissa, ) = comptroller.markets(address(ctoken));
heap.collateralFactorMantissa == 0 ||
!comptroller.checkMembership(account, ctoken)
) {
return (heap.balanceOfUnderlying, heap.underlyingLiquidity);
}
heap.liquidity,
mul_(
)
);
if (heapError(heap)) {
return (0, 0);
}
heap.maxRedeemable = min(heap.maxRedeemable, heap.balanceOfUnderlying);
heap.maxRedeemable,
sub_(
mul_ScalarTruncate(
heap.maxRedeemable
)
)
);
}
| 5,461,646 |
pragma solidity ^0.4.24;
// File: node_modules/openzeppelin-solidity/contracts/introspection/IERC165.sol
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool);
}
// File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId)
public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator)
public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId)
public;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes data
)
public;
}
// File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes data
)
public
returns(bytes4);
}
// File: node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @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;
}
}
// File: node_modules/openzeppelin-solidity/contracts/utils/Address.sol
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* 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 account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) 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(account) }
return size > 0;
}
}
// File: node_modules/openzeppelin-solidity/contracts/introspection/ERC165.sol
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
// File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
return _ownedTokensCount[owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId
)
public
{
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
)
public
{
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes _data
)
public
{
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(
address spender,
uint256 tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param owner owner of the token
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenTo(address to, uint256 tokenId) internal {
require(_tokenOwner[tokenId] == address(0));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to] = _ownedTokensCount[to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkAndCallSafeTransfer(
address from,
address to,
uint256 tokenId,
bytes _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
}
// File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
// File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor() public {
// register the supported interface to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721Enumerable);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256)
{
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenTo(address to, uint256 tokenId) internal {
super._addTokenTo(to, tokenId);
uint256 length = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address from, uint256 tokenId) internal {
super._removeTokenFrom(from, tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Reorg all tokens array
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 lastToken = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastToken;
_allTokens[lastTokenIndex] = 0;
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
_allTokensIndex[lastToken] = tokenIndex;
}
}
// File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string);
function symbol() external view returns (string);
function tokenURI(uint256 tokenId) public view returns (string);
}
// File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string internal _name;
// Token symbol
string internal _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor(string name, string symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) public view returns (string) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor(string name, string symbol) ERC721Metadata(name, symbol)
public
{
}
}
// File: node_modules/openzeppelin-solidity/contracts/access/Roles.sol
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
// File: node_modules/openzeppelin-solidity/contracts/access/roles/MinterRole.sol
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() public {
minters.add(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
minters.add(account);
emit MinterAdded(account);
}
function renounceMinter() public {
minters.remove(msg.sender);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
// File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Mintable.sol
/**
* @title ERC721Mintable
* @dev ERC721 minting logic
*/
contract ERC721Mintable is ERC721Full, MinterRole {
event MintingFinished();
bool private _mintingFinished = false;
modifier onlyBeforeMintingFinished() {
require(!_mintingFinished);
_;
}
/**
* @return true if the minting is finished.
*/
function mintingFinished() public view returns(bool) {
return _mintingFinished;
}
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param tokenId The token id to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 tokenId
)
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mint(to, tokenId);
return true;
}
function mintWithTokenURI(
address to,
uint256 tokenId,
string tokenURI
)
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
mint(to, tokenId);
_setTokenURI(tokenId, tokenURI);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting()
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mintingFinished = true;
emit MintingFinished();
return true;
}
}
// File: node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
}
/**
* @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;
}
}
// File: contracts/test.sol
contract MyTokenCollection is ERC721Full,ERC721Mintable,Ownable {
constructor() public ERC721Full("MyTokenCollection", "MTC") {}
function mintTokenCollection(string _tokenURI) public {
uint256 newTokenId = _getNextTokenId();
_mint(msg.sender, newTokenId);
_setTokenURI(newTokenId, _tokenURI);
}
function _getNextTokenId() private view returns (uint256) {
return totalSupply().add(1);
}
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(_exists(_tokenId));
super._setTokenURI(_tokenId, _uri);
}
} | Internal function to mint a new token Reverts if the given token ID already exists to address the beneficiary that will own the minted token tokenId uint256 ID of the token to be minted by the msg.sender/ | function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
| 538,546 |
./partial_match/1/0x07b10bdC1Eb8Bb885ee6Ca0458E1c276A063C8bB/sources/FirstHatcher.sol | True = Public mint is live, False = WL mint is live | function setPublicMintBool(bool _state) public onlyOwner {
publicMint = _state;
}
| 4,273,408 |
pragma solidity >=0.4.22 <0.6.0;
import "../installed_contracts/zeppelin/contracts/math/SafeMath.sol";
contract BikeSharing {
using SafeMath for uint256;
uint256 constant public MAX_BIKE_COUNT = 1000;
uint256 constant public BIKE_VALUE = 1 ether;
uint256 constant public TIME_LIMIT = 1440; // in minutes
uint256 constant public MINUTE_FACTOR = 60;
uint256 constant public RENT_FEE = 500 szabo;
// Hyperparameters
address bikeAdmin;
uint256 requiredDeposit;
uint256 fee;
// Mappings
mapping(address => Client) public clientMapping;
mapping(uint256 => Bike) bikeMapping;
mapping(uint256 => bool) isBikeActive;
mapping(address => bool) isBikeClient;
// ClientLists for count
address[] public clientList;
/*
================================================================
Data structures
================================================================
*/
enum BikeState {DEACTIVATED, AVAILABLE, IN_USE}
enum ClientState {BANNED, GOOD_TO_GO, IN_RIDE}
struct Bike {
address lastRenter;
bool condition;
bool currentlyInUse;
uint usageTime;
BikeState state;
}
struct Client {
uint256 clientListPointer;
ClientState state;
// For 1 ride, how much received and returned
uint256 received;
uint256 returned;
// Count of number of rides, number of good rides
uint256 numberRides;
uint256 goodRides;
}
/*
================================================================
Modifiers
================================================================
*/
modifier adminOnly() {
require(msg.sender == bikeAdmin);
_;
}
modifier adminExcluded() {
require(msg.sender != bikeAdmin);
_;
}
modifier bikeClientOnly(address clientAddress) {
require(isBikeClient[clientAddress] == true);
_;
}
modifier validParametersBike(uint256 bikeId) {
require(bikeId >= 0 && bikeId < MAX_BIKE_COUNT);
_;
}
modifier notNullAddress (address _address) {
require(_address != address(0));
_;
}
modifier bikeInRide (uint256 bikeId) {
require(bikeMapping[bikeId].state == BikeState.IN_USE);
_;
}
modifier bikeUser (uint256 bikeId, address clientAdr) {
require(bikeMapping[bikeId].lastRenter == clientAdr);
_;
}
modifier clientInRide (address clientAdr) {
require(clientMapping[clientAdr].state == ClientState.IN_RIDE);
_;
}
/*
================================================================
Events
================================================================
*/
event LogBikeRent(uint256 bikeId, address renter, bool status);
event LogReceivedFunds(address sender, uint256 amount);
event LogReturnedFunds(address recipient, uint256 amount);
// Fallback event
event Deposit(address indexed sender, uint256 value);
// Client creation
event ClientCreated(address clientAddress);
// Change of state events
event BikeAvailable(uint256 bikeId);
event ClientGoodToGo(address clientAddress);
event BikeInRide(uint256 bikeId);
event ClientInRide(address clientAddress);
event BikeDeactivated(uint256 bikeId);
event BikeInitiated(uint256 bikeId);
//event CleanSlate(address clientAdr);
/*
================================================================
Constructor
================================================================
*/
/// @dev Contract constructor sets the bike Admin address, the fee (by minute) and the necessary deposit
constructor() public {
bikeAdmin = msg.sender;
requiredDeposit = BIKE_VALUE;
fee = RENT_FEE;
}
/*
================================================================
Bike housekeeping
================================================================
*/
/// @dev Check if the bike is being used for the first time
/// @param bikeId the ID of a bike
/// @return True if the bike has never been used, False otherwise
function isBikeFirstUse(uint256 bikeId)
public
view
returns(bool isFirstTime)
{
return isBikeActive[bikeId] == false;
}
/// @dev Count the number of clients
/// @return Number of clients
function getClientCount()
public
view
returns(uint256 clientCount)
{
return clientList.length;
}
/// @dev Check if some address is related to a client
/// @param clientAdr the address of a client
/// @return True if the address is a client address
function isClient(address clientAdr)
public
view
returns (bool isIndeed)
{
return isBikeClient[clientAdr] == true;
}
/// @dev Check how much the contract carries value
/// @return Contract balance
function getBalance()
public
view
adminOnly
returns(uint256 balance)
{
return address(this).balance;
}
/// @dev Check the fee amount for a certain duration (in minutes) for renting the bike
/// @param duration length
/// @return Fee due
function calculateFee(uint256 duration)
public
view
returns (uint256)
{
uint256 num_minutes = duration.div(MINUTE_FACTOR);
if(num_minutes > TIME_LIMIT){
return requiredDeposit;
}
uint256 toPay = num_minutes.mul(fee);
return toPay;
}
/*
================================================================
Rent and surrender bikes
================================================================
*/
/// @dev Someone can rent a bike
/// @param bikeId the client must input the bike id
/// @return Did it succeed ? How many rides did the client make ?
function rentBike(uint256 bikeId)
public
payable
validParametersBike(bikeId)
adminExcluded
returns (bool success, uint256 nbRides)
{
// Require that the user pays the right amount for the bike
require(msg.value == requiredDeposit);
// Check if the bike is activated
if(isBikeFirstUse(bikeId)) {
bikeMapping[bikeId] = Bike(
{
lastRenter: address(0),
condition: true,
currentlyInUse: false,
usageTime: 0,
state: BikeState.DEACTIVATED
}
);
isBikeActive[bikeId] = true;
emit BikeInitiated(bikeId);
bikeMapping[bikeId].state = BikeState.AVAILABLE;
emit BikeAvailable(bikeId);
} else {
// The bike must be unused, in good condition, activated, and not in ride already
require(bikeMapping[bikeId].currentlyInUse == false);
require(bikeMapping[bikeId].condition == true);
require(bikeMapping[bikeId].state == BikeState.AVAILABLE);
}
// Check if the address is a client, if not create a struct
if(!isClient(msg.sender)){
clientMapping[msg.sender] = Client(
{
clientListPointer: 0,
state: ClientState.GOOD_TO_GO,
received: 0,
returned: 0,
numberRides: 0,
goodRides: 0
}
);
clientMapping[msg.sender].clientListPointer = clientList.push(msg.sender) - 1;
// Finally, the guy is made a client
isBikeClient[msg.sender] = true;
emit ClientCreated(msg.sender);
} else {
// The client must not be already using a scooter
require(clientMapping[msg.sender].state == ClientState.GOOD_TO_GO);
}
// Accounting
clientMapping[msg.sender].received += requiredDeposit;
emit LogReceivedFunds(msg.sender, msg.value);
// Change bike situation and state
bikeMapping[bikeId].lastRenter = msg.sender;
bikeMapping[bikeId].currentlyInUse = true;
bikeMapping[bikeId].usageTime = now;
bikeMapping[bikeId].state = BikeState.IN_USE;
emit BikeInRide(bikeId);
// Change client state and number of rides
clientMapping[msg.sender].state = ClientState.IN_RIDE;
clientMapping[msg.sender].numberRides += 1;
emit ClientInRide(msg.sender);
return(bikeMapping[bikeId].currentlyInUse, clientMapping[msg.sender].numberRides);
}
function checkBike (uint256 bikeId)
public
view
returns (address lastRenter, bool condition, bool currentlyInUse, uint usageTime, BikeState state)
{
Bike memory bike = bikeMapping[bikeId];
return (bike.lastRenter, bike.condition, bike.currentlyInUse, bike.usageTime, bike.state);
}
function checkUser (address clientAdr)
public
view
returns (uint256 clientListPointer, ClientState state, uint256 received, uint256 returned, uint256 numberRides, uint256 goodRides)
{
Client memory client = clientMapping[clientAdr];
return (client.clientListPointer, client.state, client.received, client.returned, client.numberRides, client.goodRides);
}
/// @dev Someone can stop bike usage
/// @param bikeId The client must input the bike id
/// @return Did it succeed ?
function surrenderBike(uint256 bikeId, bool newCondition)
public
bikeClientOnly(msg.sender)
validParametersBike(bikeId)
bikeInRide(bikeId)
clientInRide(msg.sender)
bikeUser(bikeId, msg.sender)
adminExcluded
returns (bool success)
{
uint256 feeCharged = calculateFee(now.sub(bikeMapping[bikeId].usageTime));
uint256 owedToClient = requiredDeposit.sub(feeCharged);
if (newCondition == false) {
owedToClient = 0;
bikeMapping[bikeId].state = BikeState.DEACTIVATED;
emit BikeDeactivated(bikeId);
} else {
clientMapping[msg.sender].goodRides += 1;
msg.sender.transfer(owedToClient);
clientMapping[msg.sender].returned += owedToClient;
emit LogReturnedFunds(msg.sender, clientMapping[msg.sender].returned);
bikeMapping[bikeId].state = BikeState.AVAILABLE;
emit BikeAvailable(bikeId);
}
bikeMapping[bikeId].currentlyInUse = false;
// Make the client good to go
clientMapping[msg.sender].state = ClientState.GOOD_TO_GO;
emit ClientGoodToGo(msg.sender);
return true;
}
/*
================================================================
Fallback function
================================================================
*/
function ()
external
payable
{
if (msg.value > 0) {
emit Deposit(msg.sender, msg.value);
}
}
/*
================================================================
Getter functions
================================================================
*/
function getTotalRides(address clientAdr)
public
view
returns (uint256 totalRidesCount)
{
Client memory client = clientMapping[clientAdr];
return client.numberRides;
}
function getGoodRides(address clientAdr)
public
view
returns (uint256 goodRidesCount)
{
Client memory client = clientMapping[clientAdr];
return client.goodRides;
}
function getBikeValue()
public
pure
returns (uint256 bikeValue)
{
return BIKE_VALUE;
}
} | Check the fee amount for a certain duration (in minutes) for renting the bike duration length return Fee due | function calculateFee(uint256 duration)
public
view
returns (uint256)
{
uint256 num_minutes = duration.div(MINUTE_FACTOR);
if(num_minutes > TIME_LIMIT){
return requiredDeposit;
}
uint256 toPay = num_minutes.mul(fee);
return toPay;
}
Rent and surrender bikes
================================================================
| 12,824,930 |
pragma solidity ^0.4.16;
import "./OriginalCoin.sol";
import "./storage.sol";
contract Origin {
uint public amount;
uint public stake;
address public issuer;
address public fraudClaimer;
bytes32 public long;
bytes32 public lat;
bytes32 public method;
uint public timestamp;
bool public fraud;
uint public creationTime;
address[] public authorities;
uint public selectedAuthority;
uint public fraudStake;
OriginalCoin public token;
modifier ownlyIssuer() {
require (msg.sender == issuer);
_;
}
modifier noFraud() {
require (fraud == false);
_;
}
modifier fraudClaimed() {
require (fraud == true);
_;
}
modifier periodPassed() {
require (now >= creationTime + 180 seconds);
_;
}
modifier periodNotPassed() {
require (now < creationTime + 180 seconds);
_;
}
modifier enoughStakePaid() {
require (msg.value == (amount/10));
_;
}
modifier isFraudClaimer() {
require (msg.sender == fraudClaimer);
_;
}
modifier isSelectedAuthority() {
require (msg.sender == authorities[selectedAuthority]);
_;
}
function Origin(uint _amount, address _issuer,bytes32 _long, bytes32 _lat, bytes32 _method, uint _timestamp,address tokenAdress,address storageAdress) { // bytes32 _long, bytes32 _lat, bytes32 _method, uint _timestamp,address tokenAdress) {
amount = _amount;
stake = 0;
issuer = _issuer;
long = _long;
lat = _lat;
method = _method;
timestamp = _timestamp;
fraud = false;
creationTime = now;
token = OriginalCoin(tokenAdress);
/*TODO import autorities from storage.sol
address authoritiesStorage = Storage(storageAdress);
authorities = authoritiesStorage.getAuthorities();
*/
}
function claimOrigin() ownlyIssuer() noFraud() periodPassed(){
//something like that
//issuer.transfer(stake);
token.mint(issuer,amount);
}
function () payable {
//TODO use constructor function instead
stake += msg.value;
}
function fraudDetected() noFraud() periodNotPassed() {
fraud = true;
fraudClaimer = msg.sender;
}
function payFraudStake()fraudClaimed() isFraudClaimer() payable {
fraudStake += msg.value;
selectAuthority();
}
function selectAuthority() private {
selectedAuthority = uint(block.blockhash(block.number - 1)) % authorities.length;
}
function fraudDecision(bool _decision) fraudClaimed() { //TODO selectedAuthorityisSelectedAuthority() {
if(_decision) {
fraudClaimer.transfer(stake + fraudStake);
} else {
fraud = false;
}
}
}
| TODO use constructor function instead | function () payable {
stake += msg.value;
}
| 14,057,623 |
./full_match/43114/0x2dCC8408890710AA69BC0c50cf98b92B1d3eb184/sources/project_/contracts/MasterChefV2.sol | Update the given pool's Token allocation point and deposit fee. Can only be called by the owner. | function set(uint256 _pid, uint256 _allocPoint, uint16 _withdrawFeeBP, bool _withUpdate) external onlyOwner {
require(_withdrawFeeBP <= 400, "add: invalid withdrawal fee basis points");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].withdrawFeeBP = _withdrawFeeBP;
emit SetPool(_pid, _allocPoint, _withdrawFeeBP);
}
| 4,502,166 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "../openzeppelin/ERC20.sol";
import "../openzeppelin/SafeERC20.sol";
import "../openzeppelin/SafeMath.sol";
import "./LiquidityMiningStorageV1.sol";
import "./ILiquidityMiningV1.sol";
contract LiquidityMiningV1 is ILiquidityMiningV1, LiquidityMiningStorageV1 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* Constants */
uint256 public constant PRECISION = 1e12;
// Bonus multiplier for early liquidity providers.
// During bonus period each passed block will be calculated like N passed blocks, where N = BONUS_MULTIPLIER
uint256 public constant BONUS_BLOCK_MULTIPLIER = 10;
uint256 public constant SECONDS_PER_BLOCK = 30;
/* Events */
event SOVTransferred(address indexed receiver, uint256 amount);
event PoolTokenAdded(address indexed user, address indexed poolToken, uint256 allocationPoint);
event PoolTokenUpdated(address indexed user, address indexed poolToken, uint256 newAllocationPoint, uint256 oldAllocationPoint);
event Deposit(address indexed user, address indexed poolToken, uint256 amount);
event RewardClaimed(address indexed user, address indexed poolToken, uint256 amount);
event Withdraw(address indexed user, address indexed poolToken, uint256 amount);
event EmergencyWithdraw(address indexed user, address indexed poolToken, uint256 amount, uint256 accumulatedReward);
/* Modifiers */
modifier onlyBeforeMigrationGracePeriod() {
require(migrationGracePeriodState < MigrationGracePeriodStates.Started, "Forbidden: migration already started");
_;
}
modifier onlyBeforeMigrationGracePeriodFinished() {
require(migrationGracePeriodState < MigrationGracePeriodStates.Finished, "Forbidden: contract deprecated");
_;
}
modifier onlyAfterMigrationFinished() {
require(migrationGracePeriodState == MigrationGracePeriodStates.Finished, "Forbidden: migration is not over yet");
_;
}
/* Functions */
/**
* @notice Initialize mining.
*
* @param _liquidityMiningV2 The LiquidityMiningV2 contract address
*/
function initialize(address _liquidityMiningV2) external onlyAuthorized {
/// @dev Non-idempotent function. Must be called just once.
require(_liquidityMiningV2 != address(0), "Invalid address");
liquidityMiningV2 = _liquidityMiningV2;
}
/**
* @notice Sets lockedSOV contract.
* @param _lockedSOV The contract instance address of the lockedSOV vault.
*/
function setLockedSOV(ILockedSOV _lockedSOV) external onlyAuthorized {
require(address(_lockedSOV) != address(0), "Invalid lockedSOV Address.");
lockedSOV = _lockedSOV;
}
/**
* @notice Sets unlocked immediately percent.
* @param _unlockedImmediatelyPercent The % which determines how much will be unlocked immediately.
* @dev @dev 10000 is 100%
*/
function setUnlockedImmediatelyPercent(uint256 _unlockedImmediatelyPercent) external onlyAuthorized {
require(_unlockedImmediatelyPercent < 10000, "Unlocked immediately percent has to be less than 10000.");
unlockedImmediatelyPercent = _unlockedImmediatelyPercent;
}
/**
* @notice sets wrapper proxy contract
* @dev can be set to zero address to remove wrapper
*/
function setWrapper(address _wrapper) external onlyAuthorized {
wrapper = _wrapper;
}
/**
* @notice stops mining by setting end block
*/
function stopMining() public onlyAuthorized {
require(endBlock == 0, "Already stopped");
endBlock = block.number;
}
// TODO: this should only be used by the LiquidityMiningV2 contract??
/// @notice This function starts the migration process which involves two steps:
/// 1. Starts the migration grace period when people can withdraw or claim for rewards
/// 2. Stops mining, i.e., no more rewards are paid
function startMigrationGracePeriod() external onlyAuthorized onlyBeforeMigrationGracePeriod {
migrationGracePeriodState = MigrationGracePeriodStates.Started;
stopMining();
}
// TODO: this should only be used by the LiquidityMiningV2 contract??
/// @notice This function finishes the migration process disabling further withdrawals and claims
/// @dev migration grace period should have started before this function is called.
function finishMigrationGracePeriod() external onlyAuthorized onlyBeforeMigrationGracePeriodFinished {
require(migrationGracePeriodState == MigrationGracePeriodStates.Started, "Migration hasn't started yet");
migrationGracePeriodState = MigrationGracePeriodStates.Finished;
}
/**
* @notice Transfers SOV tokens to given address.
* Owner use this function to withdraw SOV from LM contract
* into another account.
* @param _receiver The address of the SOV receiver.
* @param _amount The amount to be transferred.
* */
function transferSOV(address _receiver, uint256 _amount) public onlyAuthorized {
require(_receiver != address(0), "Receiver address invalid");
require(_amount != 0, "Amount invalid");
/// @dev Do not transfer more SOV than available.
uint256 SOVBal = SOV.balanceOf(address(this));
if (_amount > SOVBal) {
_amount = SOVBal;
}
/// @dev The actual transfer.
require(SOV.transfer(_receiver, _amount), "Transfer failed");
/// @dev Event log.
emit SOVTransferred(_receiver, _amount);
}
/**
* @notice Get the missed SOV balance of LM contract.
*
* @return The amount of SOV tokens according to totalUsersBalance
* in excess of actual SOV balance of the LM contract.
* */
function getMissedBalance() external view returns (uint256) {
uint256 balance = SOV.balanceOf(address(this));
return balance >= totalUsersBalance ? 0 : totalUsersBalance.sub(balance);
}
/**
* @notice adds a new lp to the pool. Can only be called by the owner or an admin
* @param _poolToken the address of pool token
* @param _allocationPoint the allocation point (weight) for the given pool
* @param _withUpdate the flag whether we need to update all pools
*/
function add(
address _poolToken,
uint96 _allocationPoint,
bool _withUpdate
) external onlyAuthorized {
require(_allocationPoint > 0, "Invalid allocation point");
require(_poolToken != address(0), "Invalid token address");
require(poolIdList[_poolToken] == 0, "Token already added");
if (_withUpdate) {
updateAllPools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocationPoint = totalAllocationPoint.add(_allocationPoint);
poolInfoList.push(
PoolInfo({
poolToken: IERC20(_poolToken),
allocationPoint: _allocationPoint,
lastRewardBlock: lastRewardBlock,
accumulatedRewardPerShare: 0
})
);
//indexing starts from 1 in order to check whether token was already added
poolIdList[_poolToken] = poolInfoList.length;
emit PoolTokenAdded(msg.sender, _poolToken, _allocationPoint);
}
/**
* @notice updates the given pool's reward tokens allocation point
* @param _poolToken the address of pool token
* @param _allocationPoint the allocation point (weight) for the given pool
* @param _updateAllFlag the flag whether we need to update all pools
*/
function update(
address _poolToken,
uint96 _allocationPoint,
bool _updateAllFlag
) external onlyAuthorized {
if (_updateAllFlag) {
updateAllPools();
} else {
updatePool(_poolToken);
}
_updateToken(_poolToken, _allocationPoint);
}
function _updateToken(address _poolToken, uint96 _allocationPoint) internal {
uint256 poolId = _getPoolId(_poolToken);
uint256 previousAllocationPoint = poolInfoList[poolId].allocationPoint;
totalAllocationPoint = totalAllocationPoint.sub(previousAllocationPoint).add(_allocationPoint);
poolInfoList[poolId].allocationPoint = _allocationPoint;
emit PoolTokenUpdated(msg.sender, _poolToken, _allocationPoint, previousAllocationPoint);
}
/**
* @notice updates the given pools' reward tokens allocation points
* @param _poolTokens array of addresses of pool tokens
* @param _allocationPoints array of allocation points (weight) for the given pools
* @param _updateAllFlag the flag whether we need to update all pools
*/
function updateTokens(
address[] calldata _poolTokens,
uint96[] calldata _allocationPoints,
bool _updateAllFlag
) external onlyAuthorized {
require(_poolTokens.length == _allocationPoints.length, "Arrays mismatch");
if (_updateAllFlag) {
updateAllPools();
}
uint256 length = _poolTokens.length;
for (uint256 i = 0; i < length; i++) {
if (!_updateAllFlag) {
updatePool(_poolTokens[i]);
}
_updateToken(_poolTokens[i], _allocationPoints[i]);
}
}
/**
* @notice returns reward multiplier over the given _from to _to block
* @param _from the first block for a calculation
* @param _to the last block for a calculation
*/
function _getPassedBlocksWithBonusMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) {
if (_from < startBlock) {
_from = startBlock;
}
if (endBlock > 0 && _to > endBlock) {
_to = endBlock;
}
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_BLOCK_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_BLOCK_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
function _getUserAccumulatedReward(uint256 _poolId, address _user) internal view returns (uint256) {
PoolInfo storage pool = poolInfoList[_poolId];
UserInfo storage user = userInfoMap[_poolId][_user];
uint256 accumulatedRewardPerShare = pool.accumulatedRewardPerShare;
uint256 poolTokenBalance = pool.poolToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && poolTokenBalance != 0) {
(, uint256 accumulatedRewardPerShare_) = _getPoolAccumulatedReward(pool);
accumulatedRewardPerShare = accumulatedRewardPerShare.add(accumulatedRewardPerShare_);
}
return user.amount.mul(accumulatedRewardPerShare).div(PRECISION).sub(user.rewardDebt);
}
/**
* @notice returns accumulated reward
* @param _poolToken the address of pool token
* @param _user the user address
*/
function getUserAccumulatedReward(address _poolToken, address _user) external view returns (uint256) {
uint256 poolId = _getPoolId(_poolToken);
return _getUserAccumulatedReward(poolId, _user);
}
/**
* @notice returns estimated reward
* @param _poolToken the address of pool token
* @param _amount the amount of tokens to be deposited
* @param _duration the duration of liquidity providing in seconds
*/
function getEstimatedReward(
address _poolToken,
uint256 _amount,
uint256 _duration
) external view returns (uint256) {
uint256 poolId = _getPoolId(_poolToken);
PoolInfo storage pool = poolInfoList[poolId];
uint256 start = block.number;
uint256 end = start.add(_duration.div(SECONDS_PER_BLOCK));
(, uint256 accumulatedRewardPerShare) = _getPoolAccumulatedReward(pool, _amount, start, end);
return _amount.mul(accumulatedRewardPerShare).div(PRECISION);
}
/**
* @notice Updates reward variables for all pools.
* @dev Be careful of gas spending!
*/
function updateAllPools() public onlyBeforeMigrationGracePeriodFinished {
uint256 length = poolInfoList.length;
for (uint256 i = 0; i < length; i++) {
_updatePool(i);
}
}
/**
* @notice Updates reward variables of the given pool to be up-to-date
* @param _poolToken the address of pool token
*/
function updatePool(address _poolToken) public onlyBeforeMigrationGracePeriodFinished {
uint256 poolId = _getPoolId(_poolToken);
_updatePool(poolId);
}
function _updatePool(uint256 _poolId) internal {
PoolInfo storage pool = poolInfoList[_poolId];
//this pool has been updated recently
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 poolTokenBalance = pool.poolToken.balanceOf(address(this));
if (poolTokenBalance == 0) {
pool.lastRewardBlock = block.number;
return;
}
(uint256 accumulatedReward_, uint256 accumulatedRewardPerShare_) = _getPoolAccumulatedReward(pool);
pool.accumulatedRewardPerShare = pool.accumulatedRewardPerShare.add(accumulatedRewardPerShare_);
pool.lastRewardBlock = block.number;
totalUsersBalance = totalUsersBalance.add(accumulatedReward_);
}
function _getPoolAccumulatedReward(PoolInfo storage _pool) internal view returns (uint256, uint256) {
return _getPoolAccumulatedReward(_pool, 0, _pool.lastRewardBlock, block.number);
}
function _getPoolAccumulatedReward(
PoolInfo storage _pool,
uint256 _additionalAmount,
uint256 _startBlock,
uint256 _endBlock
) internal view returns (uint256, uint256) {
uint256 passedBlocks = _getPassedBlocksWithBonusMultiplier(_startBlock, _endBlock);
uint256 accumulatedReward = passedBlocks.mul(rewardTokensPerBlock).mul(_pool.allocationPoint).div(totalAllocationPoint);
uint256 poolTokenBalance = _pool.poolToken.balanceOf(address(this));
poolTokenBalance = poolTokenBalance.add(_additionalAmount);
uint256 accumulatedRewardPerShare = accumulatedReward.mul(PRECISION).div(poolTokenBalance);
return (accumulatedReward, accumulatedRewardPerShare);
}
/**
* @notice deposits pool tokens
* @param _poolToken the address of pool token
* @param _amount the amount of pool tokens
* @param _user the address of user, tokens will be deposited to it or to msg.sender
*/
function deposit(
address _poolToken,
uint256 _amount,
address _user
) external onlyBeforeMigrationGracePeriod {
_deposit(_poolToken, _amount, _user, false);
}
/**
* @notice if the lending pools directly mint/transfer tokens to this address, process it like a user deposit
* @dev only callable by the pool which issues the tokens
* @param _user the user address
* @param _amount the minted amount
*/
function onTokensDeposited(address _user, uint256 _amount) external onlyBeforeMigrationGracePeriod {
//the msg.sender is the pool token. if the msg.sender is not a valid pool token, _deposit will revert
_deposit(msg.sender, _amount, _user, true);
}
/**
* @notice internal function for depositing pool tokens
* @param _poolToken the address of pool token
* @param _amount the amount of pool tokens
* @param _user the address of user, tokens will be deposited to it
* @param alreadyTransferred true if the pool tokens have already been transferred
*/
function _deposit(
address _poolToken,
uint256 _amount,
address _user,
bool alreadyTransferred
) internal {
require(poolIdList[_poolToken] != 0, "Pool token not found");
address userAddress = _user != address(0) ? _user : msg.sender;
uint256 poolId = _getPoolId(_poolToken);
PoolInfo storage pool = poolInfoList[poolId];
UserInfo storage user = userInfoMap[poolId][userAddress];
_updatePool(poolId);
//sends reward directly to the user
_updateReward(pool, user);
if (_amount > 0) {
//receives pool tokens from msg.sender, it can be user or WrapperProxy contract
if (!alreadyTransferred) pool.poolToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
_updateRewardDebt(pool, user);
emit Deposit(userAddress, _poolToken, _amount);
}
/**
* @notice transfers reward tokens
* @param _poolToken the address of pool token
* @param _user the address of user to claim reward from (can be passed only by wrapper contract)
*/
function claimReward(address _poolToken, address _user) external onlyBeforeMigrationGracePeriodFinished {
address userAddress = _getUserAddress(_user);
uint256 poolId = _getPoolId(_poolToken);
_claimReward(poolId, userAddress, true);
}
function _claimReward(
uint256 _poolId,
address _userAddress,
bool _isStakingTokens
) internal {
PoolInfo storage pool = poolInfoList[_poolId];
UserInfo storage user = userInfoMap[_poolId][_userAddress];
_updatePool(_poolId);
_updateReward(pool, user);
_transferReward(address(pool.poolToken), user, _userAddress, _isStakingTokens, true);
_updateRewardDebt(pool, user);
}
/**
* @notice transfers reward tokens from all pools
* @param _user the address of user to claim reward from (can be passed only by wrapper contract)
*/
function claimRewardFromAllPools(address _user) external onlyBeforeMigrationGracePeriodFinished {
address userAddress = _getUserAddress(_user);
uint256 length = poolInfoList.length;
for (uint256 i = 0; i < length; i++) {
uint256 poolId = i;
_claimReward(poolId, userAddress, false);
}
lockedSOV.withdrawAndStakeTokensFrom(userAddress);
}
/**
* @notice withdraws pool tokens and transfers reward tokens
* @param _poolToken the address of pool token
* @param _amount the amount of pool tokens
* @param _user the user address will be used to process a withdrawal (can be passed only by wrapper contract)
*/
function withdraw(
address _poolToken,
uint256 _amount,
address _user
) external onlyBeforeMigrationGracePeriodFinished {
require(poolIdList[_poolToken] != 0, "Pool token not found");
address userAddress = _getUserAddress(_user);
uint256 poolId = _getPoolId(_poolToken);
PoolInfo storage pool = poolInfoList[poolId];
UserInfo storage user = userInfoMap[poolId][userAddress];
require(user.amount >= _amount, "Not enough balance");
_updatePool(poolId);
_updateReward(pool, user);
_transferReward(_poolToken, user, userAddress, false, false);
user.amount = user.amount.sub(_amount);
//msg.sender is wrapper -> send to wrapper
if (msg.sender == wrapper) {
pool.poolToken.safeTransfer(address(msg.sender), _amount);
}
//msg.sender is user or pool token (lending pool) -> send to user
else {
pool.poolToken.safeTransfer(userAddress, _amount);
}
_updateRewardDebt(pool, user);
emit Withdraw(userAddress, _poolToken, _amount);
}
function _getUserAddress(address _user) internal view returns (address) {
address userAddress = msg.sender;
if (_user != address(0)) {
//only wrapper can pass _user parameter
require(msg.sender == wrapper || poolIdList[msg.sender] != 0, "only wrapper or pools may withdraw for a user");
userAddress = _user;
}
return userAddress;
}
function _updateReward(PoolInfo storage pool, UserInfo storage user) internal {
//update user accumulated reward
if (user.amount > 0) {
//add reward for the previous amount of deposited tokens
uint256 accumulatedReward = user.amount.mul(pool.accumulatedRewardPerShare).div(PRECISION).sub(user.rewardDebt);
user.accumulatedReward = user.accumulatedReward.add(accumulatedReward);
}
}
function _updateRewardDebt(PoolInfo storage pool, UserInfo storage user) internal {
//reward accumulated before amount update (should be subtracted during next reward calculation)
user.rewardDebt = user.amount.mul(pool.accumulatedRewardPerShare).div(PRECISION);
}
/**
* @notice Send reward in SOV to the lockedSOV vault.
* @param _user The user info, to get its reward share.
* @param _userAddress The address of the user, to send SOV in its behalf.
* @param _isStakingTokens The flag whether we need to stake tokens
* @param _isCheckingBalance The flag whether we need to throw error or don't process reward if SOV balance isn't enough
*/
function _transferReward(
address _poolToken,
UserInfo storage _user,
address _userAddress,
bool _isStakingTokens,
bool _isCheckingBalance
) internal {
uint256 userAccumulatedReward = _user.accumulatedReward;
/// @dev Transfer if enough SOV balance on this LM contract.
uint256 balance = SOV.balanceOf(address(this));
if (balance >= userAccumulatedReward) {
totalUsersBalance = totalUsersBalance.sub(userAccumulatedReward);
_user.accumulatedReward = 0;
/// @dev Instead of transferring the reward to the LP (user),
/// deposit it into lockedSOV vault contract, but first
/// SOV deposit must be approved to move the SOV tokens
/// from this LM contract into the lockedSOV vault.
require(SOV.approve(address(lockedSOV), userAccumulatedReward), "Approve failed");
lockedSOV.deposit(_userAddress, userAccumulatedReward, unlockedImmediatelyPercent);
if (_isStakingTokens) {
lockedSOV.withdrawAndStakeTokensFrom(_userAddress);
}
/// @dev Event log.
emit RewardClaimed(_userAddress, _poolToken, userAccumulatedReward);
} else {
require(!_isCheckingBalance, "Claiming reward failed");
}
}
/**
* @notice withdraws pool tokens without transferring reward tokens
* @param _poolToken the address of pool token
* @dev EMERGENCY ONLY
*/
function emergencyWithdraw(address _poolToken) external onlyBeforeMigrationGracePeriodFinished {
uint256 poolId = _getPoolId(_poolToken);
PoolInfo storage pool = poolInfoList[poolId];
UserInfo storage user = userInfoMap[poolId][msg.sender];
_updatePool(poolId);
_updateReward(pool, user);
totalUsersBalance = totalUsersBalance.sub(user.accumulatedReward);
uint256 userAmount = user.amount;
uint256 userAccumulatedReward = user.accumulatedReward;
user.amount = 0;
user.rewardDebt = 0;
user.accumulatedReward = 0;
pool.poolToken.safeTransfer(address(msg.sender), userAmount);
_updateRewardDebt(pool, user);
emit EmergencyWithdraw(msg.sender, _poolToken, userAmount, userAccumulatedReward);
}
/**
* @notice returns pool id
* @param _poolToken the address of pool token
*/
function getPoolId(address _poolToken) external view returns (uint256) {
return _getPoolId(_poolToken);
}
function _getPoolId(address _poolToken) internal view returns (uint256) {
uint256 poolId = poolIdList[_poolToken];
require(poolId > 0, "Pool token not found");
return poolId - 1;
}
/**
* @notice returns count of pool tokens
*/
function getPoolLength() external view returns (uint256) {
return poolInfoList.length;
}
/**
* @notice returns list of pool token's info
*/
function getPoolInfoList() external view returns (PoolInfo[] memory) {
return poolInfoList;
}
/**
* @notice returns pool info for the given token
* @param _poolToken the address of pool token
*/
function getPoolInfo(address _poolToken) external view returns (PoolInfo memory) {
uint256 poolId = _getPoolId(_poolToken);
return poolInfoList[poolId];
}
/**
* @notice returns list of [amount, accumulatedReward] for the given user for each pool token
* @param _user the address of the user
*/
function getUserBalanceList(address _user) external view returns (uint256[2][] memory) {
uint256 length = poolInfoList.length;
uint256[2][] memory userBalanceList = new uint256[2][](length);
for (uint256 i = 0; i < length; i++) {
userBalanceList[i][0] = userInfoMap[i][_user].amount;
userBalanceList[i][1] = _getUserAccumulatedReward(i, _user);
}
return userBalanceList;
}
/**
* @notice returns UserInfo for the given pool and user
* @param _poolToken the address of pool token
* @param _user the address of the user
*/
function getUserInfo(address _poolToken, address _user) public view returns (UserInfo memory) {
uint256 poolId = _getPoolId(_poolToken);
return userInfoMap[poolId][_user];
}
/**
* @notice returns list of UserInfo for the given user for each pool token
* @param _user the address of the user
*/
function getUserInfoList(address _user) external view returns (UserInfo[] memory) {
uint256 length = poolInfoList.length;
UserInfo[] memory userInfoList = new UserInfo[](length);
for (uint256 i = 0; i < length; i++) {
userInfoList[i] = userInfoMap[i][_user];
}
return userInfoList;
}
/**
* @notice returns accumulated reward for the given user for each pool token
* @param _user the address of the user
*/
function getUserAccumulatedRewardList(address _user) external view returns (uint256[] memory) {
uint256 length = poolInfoList.length;
uint256[] memory rewardList = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
rewardList[i] = _getUserAccumulatedReward(i, _user);
}
return rewardList;
}
/**
* @notice returns the pool token balance a user has on the contract
* @param _poolToken the address of pool token
* @param _user the address of the user
*/
function getUserPoolTokenBalance(address _poolToken, address _user) external view returns (uint256) {
UserInfo memory ui = getUserInfo(_poolToken, _user);
return ui.amount;
}
/**
* @notice returns arrays with all the pools on the contract
*/
function getPoolInfoListArray()
external
view
returns (
address[] memory _poolToken,
uint96[] memory _allocationPoints,
uint256[] memory _lastRewardBlock,
uint256[] memory _accumulatedRewardPerShare
)
{
uint256 length = poolInfoList.length;
_poolToken = new address[](length);
_allocationPoints = new uint96[](length);
_lastRewardBlock = new uint256[](length);
_accumulatedRewardPerShare = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
_poolToken[i] = address(poolInfoList[i].poolToken);
_allocationPoints[i] = poolInfoList[i].allocationPoint;
_lastRewardBlock[i] = poolInfoList[i].lastRewardBlock;
_accumulatedRewardPerShare[i] = poolInfoList[i].accumulatedRewardPerShare;
}
return (_poolToken, _allocationPoints, _lastRewardBlock, _accumulatedRewardPerShare);
}
/**
* @notice returns all pools that a user has on the contract, the poolId it's the index of arrays
* @param _user the address of the user
*/
function getUserInfoListArray(address _user)
external
view
returns (
uint256[] memory _amount,
uint256[] memory _rewardDebt,
uint256[] memory _accumulatedReward
)
{
uint256 length = poolInfoList.length;
_amount = new uint256[](length);
_rewardDebt = new uint256[](length);
_accumulatedReward = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
_amount[i] = userInfoMap[i][_user].amount;
_rewardDebt[i] = userInfoMap[i][_user].rewardDebt;
_accumulatedReward[i] = userInfoMap[i][_user].accumulatedReward;
}
return (_amount, _rewardDebt, _accumulatedReward);
}
/**
* @notice send all funds from this contract to LiquidityMiningV2
*/
function migrateFunds() external onlyAuthorized onlyAfterMigrationFinished {
require(liquidityMiningV2 != address(0), "Address not initialized");
uint256 SOVBalance = SOV.balanceOf(address(this));
transferSOV(liquidityMiningV2, SOVBalance);
uint256 length = poolInfoList.length;
for (uint256 i = 0; i < length; i++) {
IERC20 poolToken = poolInfoList[i].poolToken;
uint256 balancePoolToken = poolToken.balanceOf(address(this));
poolToken.safeTransfer(liquidityMiningV2, balancePoolToken);
}
}
/**
* @notice return reward token total users balance
*/
function getTotalUsersBalance() external view returns (uint256) {
return totalUsersBalance;
}
/**
* @notice return reward token start block
*/
function getStartBlock() external view returns (uint256) {
return startBlock;
}
}
| update user accumulated rewardadd reward for the previous amount of deposited tokens | function _updateReward(PoolInfo storage pool, UserInfo storage user) internal {
if (user.amount > 0) {
uint256 accumulatedReward = user.amount.mul(pool.accumulatedRewardPerShare).div(PRECISION).sub(user.rewardDebt);
user.accumulatedReward = user.accumulatedReward.add(accumulatedReward);
}
}
| 6,361,939 |
./full_match/1/0x519AE2616E0D87dBC05c2C00757894F883cDD5d6/sources/browser/BalavaDefiPool.sol | Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance | function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "BANHMI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 5,010,801 |
pragma solidity ^0.4.23;
import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol";
contract StarNotary is ERC721 {
struct Star {
string name;
string story;
string ra;
string dec;
string mag;
}
mapping(string => uint256) starToToken;
mapping(uint256 => Star) public tokenIdToStarInfo;
mapping(uint256 => uint256) public starsForSale;
event OwnStar(address ownerAddr, string starId);
event StarOnSale(uint256 tokenId, uint256 price);
function createStar(string _name, string _story, string _ra, string _dec, string _mag, uint256 _tokenId) public {
// string memory starId = keccak256(abi.encodePacked(_ra, _dec, _mag));
string memory starId = strConcat(_ra, _dec, _mag);
require(starToToken[starId] == 0, "Star needs to be unregistered");
Star memory newStar = Star(_name, _story, _ra, _dec, _mag);
tokenIdToStarInfo[_tokenId] = newStar;
starToToken[starId] = _tokenId;
super._mint(msg.sender, _tokenId);
emit OwnStar(this.ownerOf(_tokenId), starId);
}
function putStarUpForSale(uint256 _tokenId, uint256 _price) public {
require(this.ownerOf(_tokenId) == msg.sender, "Only Star owner can sell");
starsForSale[_tokenId] = _price;
emit StarOnSale(_tokenId, _price);
}
function buyStar(uint256 _tokenId) public payable {
require(starsForSale[_tokenId] > 0, "Not for sale");
uint256 starCost = starsForSale[_tokenId];
address starOwner = this.ownerOf(_tokenId);
require(msg.value >= starCost, "Insufficient balance");
_removeTokenFrom(starOwner, _tokenId);
_addTokenTo(msg.sender, _tokenId);
starOwner.transfer(starCost);
if(msg.value > starCost) {
msg.sender.transfer(msg.value - starCost);
}
}
function strConcat(string _a, string _b, string _c) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory abc = new string(_ba.length + _bb.length + _bc.length);
bytes memory babc = bytes(abc);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) babc[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babc[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babc[k++] = _bc[i];
return string(babc);
}
}
| string memory starId = keccak256(abi.encodePacked(_ra, _dec, _mag)); | function createStar(string _name, string _story, string _ra, string _dec, string _mag, uint256 _tokenId) public {
string memory starId = strConcat(_ra, _dec, _mag);
require(starToToken[starId] == 0, "Star needs to be unregistered");
Star memory newStar = Star(_name, _story, _ra, _dec, _mag);
tokenIdToStarInfo[_tokenId] = newStar;
starToToken[starId] = _tokenId;
super._mint(msg.sender, _tokenId);
emit OwnStar(this.ownerOf(_tokenId), starId);
}
| 1,805,238 |
pragma solidity ^0.4.18; // solhint-disable-line
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
contract CelebrityToken is ERC721 {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new person comes into existence.
event Birth(uint256 tokenId, string name, address owner);
/// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
/// @dev Transfer event as defined in current draft of ERC721.
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoCelebrities"; // solhint-disable-line
string public constant SYMBOL = "CelebrityToken"; // solhint-disable-line
uint256 private startingPrice = 0.001 ether;
uint256 private constant PROMO_CREATION_LIMIT = 5000;
uint256 private firstStepLimit = 0.053613 ether;
uint256 private secondStepLimit = 0.564957 ether;
/*** STORAGE ***/
/// @dev A mapping from person IDs to the address that owns them. All persons have
/// some valid owner address.
mapping (uint256 => address) public personIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) private ownershipTokenCount;
/// @dev A mapping from PersonIDs to an address that has been approved to call
/// transferFrom(). Each Person can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public personIndexToApproved;
// @dev A mapping from PersonIDs to the price of the token.
mapping (uint256 => uint256) private personIndexToPrice;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cooAddress;
uint256 public promoCreatedCount;
/*** DATATYPES ***/
struct Person {
string name;
}
Person[] private persons;
/*** ACCESS MODIFIERS ***/
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// Access modifier for contract owner only functionality
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
_;
}
/*** CONSTRUCTOR ***/
function CelebrityToken() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
}
/*** PUBLIC FUNCTIONS ***/
/// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
personIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
/// For querying balance of a particular account
/// @param _owner The address for balance query
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
/// @dev Creates a new promo Person with the given name, with given _price and assignes it to an address.
function createPromoPerson(address _owner, string _name, uint256 _price) public onlyCOO {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
address personOwner = _owner;
if (personOwner == address(0)) {
personOwner = cooAddress;
}
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createPerson(_name, personOwner, _price);
}
/// @dev Creates a new Person with the given name.
function createContractPerson(string _name) public onlyCOO {
_createPerson(_name, address(this), startingPrice);
}
/// @notice Returns all the relevant information about a specific person.
/// @param _tokenId The tokenId of the person of interest.
function getPerson(uint256 _tokenId) public view returns (
string personName,
uint256 sellingPrice,
address owner
) {
Person storage person = persons[_tokenId];
personName = person.name;
sellingPrice = personIndexToPrice[_tokenId];
owner = personIndexToOwner[_tokenId];
}
function implementsERC721() public pure returns (bool) {
return true;
}
/// @dev Required for ERC-721 compliance.
function name() public pure returns (string) {
return NAME;
}
/// For querying owner of token
/// @param _tokenId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = personIndexToOwner[_tokenId];
require(owner != address(0));
}
function payout(address _to) public onlyCLevel {
_payout(_to);
}
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId) public payable {
address oldOwner = personIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = personIndexToPrice[_tokenId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 94), 100));
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
// Update prices
if (sellingPrice < firstStepLimit) {
// first stage
personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 94);
} else if (sellingPrice < secondStepLimit) {
// second stage
personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 94);
} else {
// third stage
personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 94);
}
_transfer(oldOwner, newOwner, _tokenId);
// Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
oldOwner.transfer(payment); //(1-0.06)
}
TokenSold(_tokenId, sellingPrice, personIndexToPrice[_tokenId], oldOwner, newOwner, persons[_tokenId].name);
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return personIndexToPrice[_tokenId];
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current COO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Required for ERC-721 compliance.
function symbol() public pure returns (string) {
return SYMBOL;
}
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = personIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
/// @param _owner The owner whose celebrity tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Persons array looking for persons belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalPersons = totalSupply();
uint256 resultIndex = 0;
uint256 personId;
for (personId = 0; personId <= totalPersons; personId++) {
if (personIndexToOwner[personId] == _owner) {
result[resultIndex] = personId;
resultIndex++;
}
}
return result;
}
}
/// For querying totalSupply of token
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) {
return persons.length;
}
/// Owner initates the transfer of the token to another account
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
/// Third-party initiates transfer of token from address _from to address _to
/// @param _from The address for the token to be transferred from.
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/*** PRIVATE FUNCTIONS ***/
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
/// For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return personIndexToApproved[_tokenId] == _to;
}
/// For creating Person
function _createPerson(string _name, address _owner, uint256 _price) private {
Person memory _person = Person({
name: _name
});
uint256 newPersonId = persons.push(_person) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newPersonId == uint256(uint32(newPersonId)));
Birth(newPersonId, _name, _owner);
personIndexToPrice[newPersonId] = _price;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newPersonId);
}
/// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == personIndexToOwner[_tokenId];
}
/// For paying out balance on contract
function _payout(address _to) private {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
/// @dev Assigns ownership of a specific Person to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of persons is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
personIndexToOwner[_tokenId] = _to;
// When creating new persons _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete personIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/// @author Artyom Harutyunyan <[email protected]>
contract CelebrityBreederToken is ERC721 {
/// @dev The Birth event is fired whenever a new person comes into existence.
event Birth(uint256 tokenId, string name, address owner);
/// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
/// @dev Transfer event as defined in current draft of ERC721.
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
event Trained(address caller, uint256 tokenId, bool generation);
event Beaten(address caller, uint256 tokenId, bool generation);
event SiringPriceEvent(address caller, uint256 tokenId, bool generation, uint price);
event SellingPriceEvent(address caller, uint256 tokenId, bool generation, uint price);
event GenesInitialisedEvent(address caller, uint256 tokenId, bool generation, uint genes);
CelebrityToken private CelGen0=CelebrityToken(0xbb5Ed1EdeB5149AF3ab43ea9c7a6963b3C1374F7); //@Artyom Pointing to original CC
CelebrityBreederToken private CelBetta=CelebrityBreederToken(0xdab64dc4a02225f76fccce35ab9ba53b3735c684); //@Artyom Pointing to betta
string public constant NAME = "CryptoCelebrityBreederCards";
string public constant SYMBOL = "CeleBreedCard";
uint256 public breedingFee = 0.01 ether;
uint256 public initialTraining = 0.00001 ether;
uint256 public initialBeating = 0.00002 ether;
uint256 private constant CreationLimitGen0 = 5000;
uint256 private constant CreationLimitGen1 = 2500000;
uint256 public constant MaxValue = 100000000 ether;
mapping (uint256 => address) public personIndexToOwnerGen1;
mapping (address => uint256) private ownershipTokenCountGen1;
mapping (uint256 => address) public personIndexToApprovedGen1;
mapping (uint256 => uint256) private personIndexToPriceGen1;
mapping (uint256 => address) public ExternalAllowdContractGen0;
mapping (uint256 => address) public ExternalAllowdContractGen1;
mapping (uint256 => uint256) public personIndexToSiringPrice0;
mapping (uint256 => uint256) public personIndexToSiringPrice1;
address public CeoAddress;
address public DevAddress;
struct Person {
string name;
string surname;
uint64 genes;
uint64 birthTime;
uint32 fatherId;
uint32 motherId;
uint32 readyToBreedWithId;
uint32 trainedcount;
uint32 beatencount;
bool readyToBreedWithGen;
bool gender;
bool fatherGeneration;
bool motherGeneration;
}
Person[] private PersonsGen0;
Person[] private PersonsGen1;
modifier onlyCEO() {
require(msg.sender == CeoAddress);
_;
}
modifier onlyDEV() {
require(msg.sender == DevAddress);
_;
}
modifier onlyPlayers() {
require(ownershipTokenCountGen1[msg.sender]>0 || CelGen0.balanceOf(msg.sender)>0);
_;
}
/// Access modifier for contract owner only functionality
/* modifier onlyTopLevel() {
require(
msg.sender == CeoAddress ||
msg.sender == DevAddress
);
_;
}
*/
function masscreate(uint256 fromindex, uint256 toindex) external onlyCEO{
string memory name; string memory surname; uint64 genes; bool gender;
for(uint256 i=fromindex;i<=toindex;i++)
{
( name, surname, genes, , , , , , gender)=CelBetta.getPerson(i,false);
_birthPerson(name, surname ,genes, gender, false);
}
}
function CelebrityBreederToken() public {
CeoAddress= msg.sender;
DevAddress= msg.sender;
}
function setBreedingFee(uint256 newfee) external onlyCEO{
breedingFee=newfee;
}
function allowexternalContract(address _to, uint256 _tokenId,bool _tokengeneration) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId, _tokengeneration));
if(_tokengeneration) {
if(_addressNotNull(_to)) {
ExternalAllowdContractGen1[_tokenId]=_to;
}
else {
delete ExternalAllowdContractGen1[_tokenId];
}
}
else {
if(_addressNotNull(_to)) {
ExternalAllowdContractGen0[_tokenId]=_to;
}
else {
delete ExternalAllowdContractGen0[_tokenId];
}
}
}
//@Artyom Required for ERC-721 compliance.
function approve(address _to, uint256 _tokenId) public { //@Artyom only gen1
// Caller must own token.
require(_owns(msg.sender, _tokenId, true));
personIndexToApprovedGen1[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
// @Artyom Required for ERC-721 compliance.
//@Artyom only gen1
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCountGen1[_owner];
}
function getPerson(uint256 _tokenId,bool generation) public view returns ( string name, string surname, uint64 genes,uint64 birthTime, uint32 readyToBreedWithId, uint32 trainedcount,uint32 beatencount,bool readyToBreedWithGen, bool gender) {
Person person;
if(generation==false) {
person = PersonsGen0[_tokenId];
}
else {
person = PersonsGen1[_tokenId];
}
name = person.name;
surname=person.surname;
genes=person.genes;
birthTime=person.birthTime;
readyToBreedWithId=person.readyToBreedWithId;
trainedcount=person.trainedcount;
beatencount=person.beatencount;
readyToBreedWithGen=person.readyToBreedWithGen;
gender=person.gender;
}
function getPersonParents(uint256 _tokenId, bool generation) public view returns ( uint32 fatherId, uint32 motherId, bool fatherGeneration, bool motherGeneration) {
Person person;
if(generation==false) {
person = PersonsGen0[_tokenId];
}
else {
person = PersonsGen1[_tokenId];
}
fatherId=person.fatherId;
motherId=person.motherId;
fatherGeneration=person.fatherGeneration;
motherGeneration=person.motherGeneration;
}
// @Artyom Required for ERC-721 compliance.
function implementsERC721() public pure returns (bool) {
return true;
}
// @Artyom Required for ERC-721 compliance.
function name() public pure returns (string) {
return NAME;
}
// @Artyom Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
owner = personIndexToOwnerGen1[_tokenId];
require(_addressNotNull(owner));
}
//@Artyom only gen1
function purchase(uint256 _tokenId) public payable {
address oldOwner = personIndexToOwnerGen1[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = personIndexToPriceGen1[_tokenId];
personIndexToPriceGen1[_tokenId]=MaxValue;
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
// uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 94), 100));
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
_transfer(oldOwner, newOwner, _tokenId);
// Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
// oldOwner.transfer(payment); //(1-0.06) //old code for holding some percents
oldOwner.transfer(sellingPrice);
}
blankbreedingdata(_tokenId,true);
TokenSold(_tokenId, sellingPrice, personIndexToPriceGen1[_tokenId], oldOwner, newOwner, PersonsGen1[_tokenId].name);
msg.sender.transfer(purchaseExcess);
}
//@Artyom only gen1
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return personIndexToPriceGen1[_tokenId];
}
function setCEO(address _newCEO) external onlyCEO {
require(_addressNotNull(_newCEO));
CeoAddress = _newCEO;
}
//@Artyom only gen1
function setprice(uint256 _tokenId, uint256 _price) public {
require(_owns(msg.sender, _tokenId, true));
if(_price<=0 || _price>=MaxValue) {
personIndexToPriceGen1[_tokenId]=MaxValue;
}
else {
personIndexToPriceGen1[_tokenId]=_price;
}
SellingPriceEvent(msg.sender,_tokenId,true,_price);
}
function setDEV(address _newDEV) external onlyDEV {
require(_addressNotNull(_newDEV));
DevAddress = _newDEV;
}
// @Artyom Required for ERC-721 compliance.
function symbol() public pure returns (string) {
return SYMBOL;
}
// @Artyom Required for ERC-721 compliance.
//@Artyom only gen1
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = personIndexToOwnerGen1[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approvedGen1(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
//@Artyom only gen1
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
}
else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalPersons = totalSupply();
uint256 resultIndex = 0;
uint256 personId;
for (personId = 0; personId <= totalPersons; personId++) {
if (personIndexToOwnerGen1[personId] == _owner) {
result[resultIndex] = personId;
resultIndex++;
}
}
return result;
}
}
// @Artyom Required for ERC-721 compliance.
//@Artyom only gen1
function totalSupply() public view returns (uint256 total) {
return PersonsGen1.length;
}
// @Artyom Required for ERC-721 compliance.
//@Artyom only gen1
function transfer( address _to, uint256 _tokenId) public {
require(_owns(msg.sender, _tokenId, true));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
// @Artyom Required for ERC-721 compliance.
//@Artyom only gen1
function transferFrom(address _from, address _to, uint256 _tokenId) public {
require(_owns(_from, _tokenId, true));
require(_approvedGen1(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
/// For checking approval of transfer for address _to
function _approvedGen1(address _to, uint256 _tokenId) private view returns (bool) {
return personIndexToApprovedGen1[_tokenId] == _to;
}
//@Artyom only gen0
function createPersonGen0(string _name, string _surname,uint64 _genes, bool _gender) external onlyCEO returns(uint256) {
return _birthPerson(_name, _surname ,_genes, _gender, false);
}
function SetGene(uint256 tokenId,bool generation, uint64 newgene) public {
require(_owns(msg.sender, tokenId, generation) || msg.sender==CeoAddress);
require(newgene<=9999999999 && newgene>=10);
Person person; //@Artyom reference
if (generation==false) {
person = PersonsGen0[tokenId];
}
else {
person = PersonsGen1[tokenId];
}
require(person.genes<=90);
uint64 _gene=newgene;
uint64 _pointCount=0;
for(uint i=0;i<10;i++) {
_pointCount+=_gene%10;
_gene=_gene/10;
}
// log(_pointCount,person.genes);
require(_pointCount==person.genes);
person.genes=newgene;
GenesInitialisedEvent(msg.sender,tokenId,generation,newgene);
}
function breed(uint256 _mypersonid, bool _mypersongeneration, uint256 _withpersonid, bool _withpersongeneration, string _boyname, string _girlname) public payable { //@Artyom mother
require(_owns(msg.sender, _mypersonid, _mypersongeneration));
require(CreationLimitGen1>totalSupply()+1);
//Mother
Person person; //@Artyom reference
if(_mypersongeneration==false) {
person = PersonsGen0[_mypersonid];
}
else {
person = PersonsGen1[_mypersonid];
require(person.gender==false); //@Artyom checking gender for gen1 to be mother in this case
}
require(person.genes>90);//@Artyom if its unlocked
uint64 genes1=person.genes;
//Father
if(_withpersongeneration==false) {
person = PersonsGen0[_withpersonid];
}
else {
person = PersonsGen1[_withpersonid];
}
require(readyTobreed(_mypersonid, _mypersongeneration, _withpersonid, _withpersongeneration));
require(breedingFee<=msg.value);
delete person.readyToBreedWithId;
person.readyToBreedWithGen=false;
// uint64 genes2=person.genes;
uint64 _generatedGen;
bool _gender;
(_generatedGen,_gender)=_generateGene(genes1,person.genes,_mypersonid,_withpersonid);
if(_gender) {
_girlname=_boyname; //@Artyom if gender is true/1 then it should take the boyname
}
uint newid=_birthPerson(_girlname, person.surname, _generatedGen, _gender, true);
PersonsGen1[newid].fatherGeneration=_withpersongeneration; // @ Artyom, did here because stack too deep for function
PersonsGen1[newid].motherGeneration=_mypersongeneration;
PersonsGen1[newid].fatherId=uint32(_withpersonid);
PersonsGen1[newid].motherId=uint32(_mypersonid);
_payout();
}
function breedOnAuction(uint256 _mypersonid, bool _mypersongeneration, uint256 _withpersonid, bool _withpersongeneration, string _boyname, string _girlname) public payable { //@Artyom mother
require(_owns(msg.sender, _mypersonid, _mypersongeneration));
require(CreationLimitGen1>totalSupply()+1);
require(!(_mypersonid==_withpersonid && _mypersongeneration==_withpersongeneration));// @Artyom not to breed with self
require(!((_mypersonid==0 && _mypersongeneration==false) || (_withpersonid==0 && _withpersongeneration==false))); //Not to touch Satoshi
//Mother
Person person; //@Artyom reference
if(_mypersongeneration==false) {
person = PersonsGen0[_mypersonid];
}
else {
person = PersonsGen1[_mypersonid];
require(person.gender==false); //@Artyom checking gender for gen1 to be mother in this case
}
require(person.genes>90);//@Artyom if its unlocked
address owneroffather;
uint256 _siringprice;
uint64 genes1=person.genes;
//Father
if(_withpersongeneration==false) {
person = PersonsGen0[_withpersonid];
_siringprice=personIndexToSiringPrice0[_withpersonid];
owneroffather=CelGen0.ownerOf(_withpersonid);
}
else {
person = PersonsGen1[_withpersonid];
_siringprice=personIndexToSiringPrice1[_withpersonid];
owneroffather= personIndexToOwnerGen1[_withpersonid];
}
require(_siringprice>0 && _siringprice<MaxValue);
require((breedingFee+_siringprice)<=msg.value);
// uint64 genes2=;
uint64 _generatedGen;
bool _gender;
(_generatedGen,_gender)=_generateGene(genes1,person.genes,_mypersonid,_withpersonid);
if(_gender) {
_girlname=_boyname; //@Artyom if gender is true/1 then it should take the boyname
}
uint newid=_birthPerson(_girlname, person.surname, _generatedGen, _gender, true);
PersonsGen1[newid].fatherGeneration=_withpersongeneration; // @ Artyom, did here because stack too deep for function
PersonsGen1[newid].motherGeneration=_mypersongeneration;
PersonsGen1[newid].fatherId=uint32(_withpersonid);
PersonsGen1[newid].motherId=uint32(_mypersonid);
owneroffather.transfer(_siringprice);
_payout();
}
function prepareToBreed(uint256 _mypersonid, bool _mypersongeneration, uint256 _withpersonid, bool _withpersongeneration, uint256 _siringprice) external { //@Artyom father
require(_owns(msg.sender, _mypersonid, _mypersongeneration));
Person person; //@Artyom reference
if(_mypersongeneration==false) {
person = PersonsGen0[_mypersonid];
personIndexToSiringPrice0[_mypersonid]=_siringprice;
}
else {
person = PersonsGen1[_mypersonid];
require(person.gender==true);//@Artyom for gen1 checking genders to be male
personIndexToSiringPrice1[_mypersonid]=_siringprice;
}
require(person.genes>90);//@Artyom if its unlocked
person.readyToBreedWithId=uint32(_withpersonid);
person.readyToBreedWithGen=_withpersongeneration;
SiringPriceEvent(msg.sender,_mypersonid,_mypersongeneration,_siringprice);
}
function readyTobreed(uint256 _mypersonid, bool _mypersongeneration, uint256 _withpersonid, bool _withpersongeneration) public view returns(bool) {
if (_mypersonid==_withpersonid && _mypersongeneration==_withpersongeneration) //Not to fuck Themselves
return false;
if((_mypersonid==0 && _mypersongeneration==false) || (_withpersonid==0 && _withpersongeneration==false)) //Not to touch Satoshi
return false;
Person withperson; //@Artyom reference
if(_withpersongeneration==false) {
withperson = PersonsGen0[_withpersonid];
}
else {
withperson = PersonsGen1[_withpersonid];
}
if(withperson.readyToBreedWithGen==_mypersongeneration) {
if(withperson.readyToBreedWithId==_mypersonid) {
return true;
}
}
return false;
}
function _birthPerson(string _name, string _surname, uint64 _genes, bool _gender, bool _generation) private returns(uint256) { // about this steps
Person memory _person = Person({
name: _name,
surname: _surname,
genes: _genes,
birthTime: uint64(now),
fatherId: 0,
motherId: 0,
readyToBreedWithId: 0,
trainedcount: 0,
beatencount: 0,
readyToBreedWithGen: false,
gender: _gender,
fatherGeneration: false,
motherGeneration: false
});
uint256 newPersonId;
if(_generation==false) {
newPersonId = PersonsGen0.push(_person) - 1;
}
else {
newPersonId = PersonsGen1.push(_person) - 1;
personIndexToPriceGen1[newPersonId] = MaxValue; //@Artyom indicating not for sale
// per ERC721 draft-This will assign ownership, and also emit the Transfer event as
_transfer(address(0), msg.sender, newPersonId);
}
Birth(newPersonId, _name, msg.sender);
return newPersonId;
}
function _generateGene(uint64 _genes1,uint64 _genes2,uint256 _mypersonid,uint256 _withpersonid) private returns(uint64,bool) {
uint64 _gene;
uint64 _gene1;
uint64 _gene2;
uint64 _rand;
uint256 _finalGene=0;
bool gender=false;
for(uint i=0;i<10;i++) {
_gene1 =_genes1%10;
_gene2=_genes2%10;
_genes1=_genes1/10;
_genes2=_genes2/10;
_rand=uint64(keccak256(block.blockhash(block.number), i, now,_mypersonid,_withpersonid))%10000;
_gene=(_gene1+_gene2)/2;
if(_rand<26) {
_gene-=3;
}
else if(_rand<455) {
_gene-=2;
}
else if(_rand<3173) {
_gene-=1;
}
else if(_rand<6827) {
}
else if(_rand<9545) {
_gene+=1;
}
else if(_rand<9974) {
_gene+=2;
}
else if(_rand<10000) {
_gene+=3;
}
if(_gene>12) //@Artyom to avoid negative overflow
_gene=0;
if(_gene>9)
_gene=9;
_finalGene+=(uint(10)**i)*_gene;
}
if(uint64(keccak256(block.blockhash(block.number), 11, now,_mypersonid,_withpersonid))%2>0)
gender=true;
return(uint64(_finalGene),gender);
}
function _owns(address claimant, uint256 _tokenId,bool _tokengeneration) private view returns (bool) {
if(_tokengeneration) {
return ((claimant == personIndexToOwnerGen1[_tokenId]) || (claimant==ExternalAllowdContractGen1[_tokenId]));
}
else {
return ((claimant == CelGen0.personIndexToOwner(_tokenId)) || (claimant==ExternalAllowdContractGen0[_tokenId]));
}
}
function _payout() private {
DevAddress.transfer((this.balance/10)*3);
CeoAddress.transfer((this.balance/10)*7);
}
// @Artyom Required for ERC-721 compliance.
//@Artyom only gen1
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of persons is capped to 2^32 we can't overflow this
ownershipTokenCountGen1[_to]++;
//transfer ownership
personIndexToOwnerGen1[_tokenId] = _to;
// When creating new persons _from is 0x0, but we can't account that address.
if (_addressNotNull(_from)) {
ownershipTokenCountGen1[_from]--;
// clear any previously approved ownership exchange
blankbreedingdata(_tokenId,true);
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
function blankbreedingdata(uint256 _personid, bool _persongeneration) private{
Person person;
if(_persongeneration==false) {
person = PersonsGen0[_personid];
delete ExternalAllowdContractGen0[_personid];
delete personIndexToSiringPrice0[_personid];
}
else {
person = PersonsGen1[_personid];
delete ExternalAllowdContractGen1[_personid];
delete personIndexToSiringPrice1[_personid];
delete personIndexToApprovedGen1[_personid];
}
delete person.readyToBreedWithId;
delete person.readyToBreedWithGen;
}
function train(uint256 personid, bool persongeneration, uint8 gene) external payable onlyPlayers {
require(gene>=0 && gene<10);
uint256 trainingPrice=checkTrainingPrice(personid,persongeneration);
require(msg.value >= trainingPrice);
Person person;
if(persongeneration==false) {
person = PersonsGen0[personid];
}
else {
person = PersonsGen1[personid];
}
require(person.genes>90);//@Artyom if its unlocked
uint gensolo=person.genes/(uint(10)**gene);
gensolo=gensolo%10;
require(gensolo<9); //@Artyom not to train after 9
person.genes+=uint64(10)**gene;
person.trainedcount++;
uint256 purchaseExcess = SafeMath.sub(msg.value, trainingPrice);
msg.sender.transfer(purchaseExcess);
_payout();
Trained(msg.sender, personid, persongeneration);
}
function beat(uint256 personid, bool persongeneration, uint8 gene) external payable onlyPlayers {
require(gene>=0 && gene<10);
uint256 beatingPrice=checkBeatingPrice(personid,persongeneration);
require(msg.value >= beatingPrice);
Person person;
if(persongeneration==false) {
person = PersonsGen0[personid];
}
else {
person = PersonsGen1[personid];
}
require(person.genes>90);//@Artyom if its unlocked
uint gensolo=person.genes/(uint(10)**gene);
gensolo=gensolo%10;
require(gensolo>0);
person.genes-=uint64(10)**gene;
person.beatencount++;
uint256 purchaseExcess = SafeMath.sub(msg.value, beatingPrice);
msg.sender.transfer(purchaseExcess);
_payout();
Beaten(msg.sender, personid, persongeneration);
}
function checkTrainingPrice(uint256 personid, bool persongeneration) view returns (uint256) {
Person person;
if(persongeneration==false) {
person = PersonsGen0[personid];
}
else {
person = PersonsGen1[personid];
}
uint256 _trainingprice= (uint(2)**person.trainedcount) * initialTraining;
if (_trainingprice > 5 ether)
_trainingprice=5 ether;
return _trainingprice;
}
function checkBeatingPrice(uint256 personid, bool persongeneration) view returns (uint256) {
Person person;
if(persongeneration==false) {
person = PersonsGen0[personid];
}
else {
person = PersonsGen1[personid];
}
uint256 _beatingprice=(uint(2)**person.beatencount) * initialBeating;
if (_beatingprice > 7 ether)
_beatingprice=7 ether;
return _beatingprice;
}
} | @Artyom Required for ERC-721 compliance.@Artyom only gen1 | function totalSupply() public view returns (uint256 total) {
return PersonsGen1.length;
}
| 12,049,406 |
./full_match/43114/0x21C971D78E1A398710d964Ed1AC4C80E5940ed25/sources/contracts/strategies/SimpleHoldingStrategy.sol | Stability fee if any | function stabilityFeePer10k(address token)
public
view
override
returns (uint256)
{
return _stabilityFeePer10k[token];
}
| 4,620,914 |
// SPDX-License-Identifier: MIT
// Created by Flux Team
pragma solidity ^0.6.8;
import "./Market.sol";
import "./IMarket.sol";
import "./Interface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title MarketERC777 是 Flux 协议中用于封装 ERC20 的标的资产合约借贷市场
* @author Flux
*/
contract MarketERC20 is Market, IMarketERC20 {
/**
@notice 取款(兑换标的资产)
@param ctokens 待用于兑换标的资产数量
*/
function redeem(uint256 ctokens) external override {
_redeem(msg.sender, msg.sender, ctokens, true);
}
function borrow(uint256 ctokens) external override {
_borrow(msg.sender, ctokens);
}
function underlyingTransferIn(address sender, uint256 amount) internal virtual override returns (uint256) {
underlying.safeTransferFrom(sender, address(this), amount);
return amount;
}
function underlyingTransferOut(address receipt, uint256 amount) internal virtual override returns (uint256) {
// skip transfer to myself
if (receipt == address(this)) {
return amount;
}
underlying.safeTransfer(receipt, amount);
return amount;
}
function repay(uint256 amount) external override {
_repay(msg.sender, amount);
}
function mint(uint256 amount) external override {
_supply(msg.sender, amount);
}
function depositFor(address receiver, uint256 amount) external {
_supply(receiver, amount);
}
function withdraw(address to, uint256 ctokens) external {
require(to != address(0), "address is empty");
_redeem(msg.sender, to, ctokens, true);
}
}
| skip transfer to myself | function underlyingTransferOut(address receipt, uint256 amount) internal virtual override returns (uint256) {
if (receipt == address(this)) {
return amount;
}
underlying.safeTransfer(receipt, amount);
return amount;
}
| 2,521,142 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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);
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
contract Migrations {
address public owner;
uint256 public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint256 completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
library FixedPoint {
using SafeMath for uint256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
abstract contract Balancer {
function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual view returns (uint256 spotPrice);
}
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
}
abstract contract OneSplit {
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public virtual view returns (uint256 returnAmount, uint256[] memory distribution);
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public virtual payable returns (uint256 returnAmount);
}
abstract contract Uniswap {
// Called after every swap showing the new uniswap "price" for this token pair.
event Sync(uint112 reserve0, uint112 reserve1);
}
contract BalancerMock is Balancer {
uint256 price = 0;
// these params arent used in the mock, but this is to maintain compatibility with balancer API
function getSpotPriceSansFee(address tokenIn, address tokenOut)
external
virtual
override
view
returns (uint256 spotPrice)
{
return price;
}
// this is not a balancer call, but for testing for changing price.
function setPrice(uint256 newPrice) external {
price = newPrice;
}
}
contract FixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
contract OneSplitMock is OneSplit {
address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
mapping(bytes32 => uint256) prices;
receive() external payable {}
// Sets price of 1 FROM = <PRICE> TO
function setPrice(
address from,
address to,
uint256 price
) external {
prices[keccak256(abi.encodePacked(from, to))] = price;
}
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public override view returns (uint256 returnAmount, uint256[] memory distribution) {
returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
return (returnAmount, distribution);
}
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public override payable returns (uint256 returnAmount) {
uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
require(amountReturn >= minReturn, "Min Amount not reached");
if (destToken == ETH_ADDRESS) {
msg.sender.transfer(amountReturn);
} else {
require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed");
}
}
}
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
contract ReentrancyChecker {
bytes public txnData;
bool hasBeenCalled;
// Used to prevent infinite cycles where the reentrancy is cycled forever.
modifier skipIfReentered {
if (hasBeenCalled) {
return;
}
hasBeenCalled = true;
_;
hasBeenCalled = false;
}
function setTransactionData(bytes memory _txnData) public {
txnData = _txnData;
}
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool success) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
}
fallback() external skipIfReentered {
// Attampt to re-enter with the set txnData.
bool success = _executeCall(msg.sender, 0, txnData);
// Fail if the call succeeds because that means the re-entrancy was successful.
require(!success, "Re-entrancy was successful");
}
}
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
contract UniswapMock is Uniswap {
function setPrice(uint112 reserve0, uint112 reserve1) external {
emit Sync(reserve0, reserve1);
}
}
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
abstract contract FeePayer is Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees {
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) nonReentrant() {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) {
StoreInterface store = _getStore();
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral from which to pay fees.
if (collateralPool.isEqual(0)) {
return totalPaid;
}
// Exit early if fees were already paid during this block.
if (lastPaymentTime == time) {
return totalPaid;
}
(FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee(
lastPaymentTime,
time,
collateralPool
);
lastPaymentTime = time;
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return totalPaid;
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() public view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC");
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _pfc() internal virtual view returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
receive() external payable {
deposit();
}
fallback() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
function approve(address guy, uint256 wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint256 wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(
address src,
address dst,
uint256 wad
) public returns (bool) {
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
}
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist = AddressWhitelist(
finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)
);
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingInterface.Commitment[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingInterface.Reveal[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingInterface.PendingRequest[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingInterface) {
return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingInterface.Phase) {
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
}
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
interface OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) external;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) external view returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) external view returns (int256);
}
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] calldata commits) external virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) external virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] calldata reveals) external virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external virtual view returns (PendingRequest[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external virtual view returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external virtual view returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
}
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) external override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) external override view returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) external override view returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
contract Umip15Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
}
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set current Voting contract to migrated.
existingVoting.setMigrated(newVoting);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
}
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
contract DepositBox is FeePayer, AdministrateeInterface, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(
exchangeRate
);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address excessTokenBeneficiary;
}
// - Address of TokenFactory to pass into newly constructed ExpiringMultiParty contracts
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params));
_registerContract(new address[](0), address(derivative));
emit CreatedExpiringMultiParty(address(derivative), msg.sender);
return address(derivative);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.tokenFactoryAddress = tokenFactoryAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.excessTokenBeneficiary != address(0), "Token Beneficiary cannot be 0x0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.syntheticName = params.syntheticName;
constructorParams.syntheticSymbol = params.syntheticSymbol;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPct = params.disputeBondPct;
constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.excessTokenBeneficiary = params.excessTokenBeneficiary;
}
}
contract PricelessPositionManager is FeePayer, AdministrateeInterface {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// The excessTokenBeneficiary of any excess tokens added to the contract.
address public excessTokenBeneficiary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _syntheticName name for the token contract that will be deployed.
* @param _syntheticSymbol symbol for the token contract that will be deployed.
* @param _tokenFactoryAddress deployed UMA token factory to create the synthetic token.
* @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* @param _excessTokenBeneficiary Beneficiary to which all excess token balances that accrue in the contract can be
* sent.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
string memory _syntheticName,
string memory _syntheticSymbol,
address _tokenFactoryAddress,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _excessTokenBeneficiary
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime(), "Invalid expiration in future");
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
TokenFactory tf = TokenFactory(_tokenFactoryAddress);
tokenCurrency = tf.createToken(_syntheticName, _syntheticSymbol, 18);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
excessTokenBeneficiary = _excessTokenBeneficiary;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer");
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
),
"Sponsor already has position"
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime(),
"Invalid transfer request"
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0, "No pending transfer");
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the witdrawl. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)),
"Invalid collateral amount"
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue), "Minting synthetic tokens failed");
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding), "Invalid token amount");
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(
_getFeeAdjustedCollateral(positionData.rawCollateral)
);
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePrice(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(
positionCollateral
)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout = FixedPoint.min(
_getFeeAdjustedCollateral(rawTotalPositionCollateral),
totalRedeemableCollateral
);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// The final fee for this request is paid out of the contract rather than by the caller.
_payFinalFees(address(this), _computeFinalFees());
_requestOraclePrice(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress(), "Caller not Governor");
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePrice(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary.
* @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token.
* @param token address of the ERC20 token whose excess balance should be drained.
*/
function trimExcess(IERC20 token) external fees() nonReentrant() returns (FixedPoint.Unsigned memory amount) {
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(token.balanceOf(address(this)));
if (address(token) == address(collateralCurrency)) {
// If it is the collateral currency, send only the amount that the contract is not tracking.
// Note: this could be due to rounding error or balance-changing tokens, like aTokens.
amount = balance.sub(_pfc());
} else {
// If it's not the collateral currency, send the entire balance.
amount = balance;
}
token.safeTransfer(excessTokenBeneficiary, amount.rawValue);
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global = _getCollateralizationRatio(
_getFeeAdjustedCollateral(rawTotalPositionCollateral),
totalTokensOutstanding
);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
}
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external override view returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external override view returns (bool) {
return supportedIdentifiers[identifier];
}
}
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external override view returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external override view returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external override view returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public override view returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external override payable {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external override view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(
paymentDelay.div(SECONDS_PER_WEEK)
);
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external override view returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
contract Voting is Testable, Ownable, OracleInterface, VotingInterface {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) external override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
bytes32 priceRequestId = _encodePriceRequest(identifier, time);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) external override view onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time);
return _hasPrice;
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time)
external
override
view
onlyRegisteredContract()
returns (int256)
{
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Commit, "Cannot commit in reveal phase");
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external override onlyIfNotMigrated() {
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override onlyIfNotMigrated() {
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from
// revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, roundId, identifier)) == voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, balance.rawValue);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public {
commitVote(identifier, time, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] calldata commits) external override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] calldata reveals) external override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt);
}
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
uint256 blockTime = getCurrentTime();
require(roundId < voteTiming.computeCurrentRoundId(blockTime), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = blockTime > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(
votingToken.balanceOfAt(voterAddress, round.snapshotId)
);
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(
votingToken.totalSupplyAt(round.snapshotId)
);
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests() external override view returns (PendingRequest[] memory) {
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequest[] memory unresolved = new PendingRequest[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequest({
identifier: priceRequest.identifier,
time: priceRequest.time
});
numUnresolved++;
}
}
PendingRequest[] memory pendingRequests = new PendingRequest[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external override view returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external override view returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external onlyOwner {
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public onlyOwner {
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public onlyOwner {
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public onlyOwner {
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(bytes32 identifier, uint256 time)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound)
);
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(bytes32 identifier, uint256 time) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time)];
}
function _encodePriceRequest(bytes32 identifier, uint256 time) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound)
);
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound)
);
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
*/
constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
}
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address finderAddress;
address tokenFactoryAddress;
address timerAddress;
address excessTokenBeneficiary;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPct;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPct;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 withdrawalAmount,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.syntheticName,
params.syntheticSymbol,
params.tokenFactoryAddress,
params.minSponsorTokens,
params.timerAddress,
params.excessTokenBeneficiary
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%");
require(
params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1),
"Rewards are more than 100%"
);
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(
ratio
);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.PreDispute,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp <= getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(liquidationLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPct` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* the sponsor, liquidator, and/or disputer can call this method to receive payments.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* Once all collateral is withdrawn, delete the liquidation data.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return amountWithdrawn the total amount of underlying returned from the liquidation.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(msg.sender == liquidation.disputer) ||
(msg.sender == liquidation.liquidator) ||
(msg.sender == liquidation.sponsor),
"Caller cannot withdraw rewards"
);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(
feeAttenuation
);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation can withdraw different amounts.
// Once a caller has been paid their address deleted from the struct.
// This prevents them from being paid multiple from times the same liquidation.
FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0);
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users can withdraw from the contract.
if (msg.sender == liquidation.disputer) {
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
withdrawalAmount = withdrawalAmount.add(payToDisputer);
delete liquidation.disputer;
}
if (msg.sender == liquidation.sponsor) {
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue);
FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral);
withdrawalAmount = withdrawalAmount.add(payToSponsor);
delete liquidation.sponsor;
}
if (msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(
disputerDisputeReward
);
withdrawalAmount = withdrawalAmount.add(payToLiquidator);
delete liquidation.liquidator;
}
// Free up space once all collateral is withdrawn by removing the liquidation object from the array.
if (
liquidation.disputer == address(0) &&
liquidation.sponsor == address(0) &&
liquidation.liquidator == address(0)
) {
delete liquidations[sponsor][liquidationId];
}
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee);
delete liquidations[sponsor][liquidationId];
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.PreDispute && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + returned final fee
withdrawalAmount = collateral.add(finalFee);
delete liquidations[sponsor][liquidationId];
}
require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount");
// Decrease the total collateral held in liquidatable by the amount withdrawn.
amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount);
emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state, settlementPrice.rawValue);
// Transfer amount withdrawn from this contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
return amountWithdrawn;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == PendingDispute and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.PendingDispute) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(
liquidation.settlementPrice
);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal override view returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
}
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
| Create an instance of the oracle and get the price. If the price is not resolved revert. For now we don't want to deal with negative prices in positions. | function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
| 7,360,558 |
pragma solidity ^0.5.10;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: contracts/commons/Ownable.sol
pragma solidity ^0.5.10;
contract Ownable {
address public owner;
event TransferOwnership(address _from, address _to);
constructor() public {
owner = msg.sender;
emit TransferOwnership(address(0), msg.sender);
}
modifier onlyOwner() {
require(msg.sender == owner, "only owner");
_;
}
function setOwner(address _owner) external onlyOwner {
emit TransferOwnership(owner, _owner);
owner = _owner;
}
}
// File: contracts/commons/StorageUnit.sol
pragma solidity ^0.5.10;
contract StorageUnit {
address private owner;
mapping(bytes32 => bytes32) private store;
constructor() public {
owner = msg.sender;
}
function write(bytes32 _key, bytes32 _value) external {
/* solium-disable-next-line */
require(msg.sender == owner);
store[_key] = _value;
}
function read(bytes32 _key) external view returns (bytes32) {
return store[_key];
}
}
// File: contracts/utils/IsContract.sol
pragma solidity ^0.5.10;
library IsContract {
function isContract(address _addr) internal view returns (bool) {
bytes32 codehash;
/* solium-disable-next-line */
assembly { codehash := extcodehash(_addr) }
return codehash != bytes32(0) && codehash != bytes32(0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
}
// File: contracts/utils/DistributedStorage.sol
pragma solidity ^0.5.10;
library DistributedStorage {
function contractSlot(bytes32 _struct) private view returns (address) {
return address(
uint256(
keccak256(
abi.encodePacked(
byte(0xff),
address(this),
_struct,
keccak256(type(StorageUnit).creationCode)
)
)
)
);
}
function deploy(bytes32 _struct) private {
bytes memory slotcode = type(StorageUnit).creationCode;
/* solium-disable-next-line */
assembly{ pop(create2(0, add(slotcode, 0x20), mload(slotcode), _struct)) }
}
function write(
bytes32 _struct,
bytes32 _key,
bytes32 _value
) internal {
StorageUnit store = StorageUnit(contractSlot(_struct));
if (!IsContract.isContract(address(store))) {
deploy(_struct);
}
/* solium-disable-next-line */
(bool success, ) = address(store).call(
abi.encodeWithSelector(
store.write.selector,
_key,
_value
)
);
require(success, "error writing storage");
}
function read(
bytes32 _struct,
bytes32 _key
) internal view returns (bytes32) {
StorageUnit store = StorageUnit(contractSlot(_struct));
if (!IsContract.isContract(address(store))) {
return bytes32(0);
}
/* solium-disable-next-line */
(bool success, bytes memory data) = address(store).staticcall(
abi.encodeWithSelector(
store.read.selector,
_key
)
);
require(success, "error reading storage");
return abi.decode(data, (bytes32));
}
}
// File: contracts/utils/SafeMath.sol
pragma solidity ^0.5.10;
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x + y;
require(z >= x, "Add overflow");
return z;
}
function sub(uint256 x, uint256 y) internal pure returns (uint256) {
require(x >= y, "Sub underflow");
return x - y;
}
function mult(uint256 x, uint256 y) internal pure returns (uint256) {
if (x == 0) {
return 0;
}
uint256 z = x * y;
require(z / x == y, "Mult overflow");
return z;
}
function div(uint256 x, uint256 y) internal pure returns (uint256) {
require(y != 0, "Div by zero");
return x / y;
}
function divRound(uint256 x, uint256 y) internal pure returns (uint256) {
require(y != 0, "Div by zero");
uint256 r = x / y;
if (x % y != 0) {
r = r + 1;
}
return r;
}
}
// File: contracts/utils/Math.sol
pragma solidity ^0.5.10;
library Math {
function orderOfMagnitude(uint256 input) internal pure returns (uint256){
uint256 counter = uint(-1);
uint256 temp = input;
do {
temp /= 10;
counter++;
} while (temp != 0);
return counter;
}
function min(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a < _b) {
return _a;
} else {
return _b;
}
}
function max(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a > _b) {
return _a;
} else {
return _b;
}
}
}
// File: contracts/utils/GasPump.sol
pragma solidity ^0.5.10;
contract GasPump {
bytes32 private stub;
modifier requestGas(uint256 _factor) {
if (tx.gasprice == 0 || gasleft() > block.gaslimit) {
uint256 startgas = gasleft();
_;
uint256 delta = startgas - gasleft();
uint256 target = (delta * _factor) / 100;
startgas = gasleft();
while (startgas - gasleft() < target) {
// Burn gas
stub = keccak256(abi.encodePacked(stub));
}
} else {
_;
}
}
}
// File: contracts/interfaces/IERC20.sol
pragma solidity ^0.5.10;
interface IERC20 {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function approve(address _spender, uint256 _value) external returns (bool success);
function balanceOf(address _owner) external view returns (uint256 balance);
}
// File: contracts/commons/AddressMinHeap.sol
pragma solidity ^0.5.10;
/*
@author Agustin Aguilar <[email protected]>
*/
library AddressMinHeap {
using AddressMinHeap for AddressMinHeap.Heap;
struct Heap {
uint256[] entries;
mapping(address => uint256) index;
}
function initialize(Heap storage _heap) internal {
require(_heap.entries.length == 0, "already initialized");
_heap.entries.push(0);
}
function encode(address _addr, uint256 _value) internal pure returns (uint256 _entry) {
/* solium-disable-next-line */
assembly {
_entry := not(or(and(0xffffffffffffffffffffffffffffffffffffffff, _addr), shl(160, _value)))
}
}
function decode(uint256 _entry) internal pure returns (address _addr, uint256 _value) {
/* solium-disable-next-line */
assembly {
let entry := not(_entry)
_addr := and(entry, 0xffffffffffffffffffffffffffffffffffffffff)
_value := shr(160, entry)
}
}
function decodeAddress(uint256 _entry) internal pure returns (address _addr) {
/* solium-disable-next-line */
assembly {
_addr := and(not(_entry), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
function top(Heap storage _heap) internal view returns(address, uint256) {
if (_heap.entries.length < 2) {
return (address(0), 0);
}
return decode(_heap.entries[1]);
}
function has(Heap storage _heap, address _addr) internal view returns (bool) {
return _heap.index[_addr] != 0;
}
function size(Heap storage _heap) internal view returns (uint256) {
return _heap.entries.length - 1;
}
function entry(Heap storage _heap, uint256 _i) internal view returns (address, uint256) {
return decode(_heap.entries[_i + 1]);
}
// RemoveMax pops off the root element of the heap (the highest value here) and rebalances the heap
function popTop(Heap storage _heap) internal returns(address _addr, uint256 _value) {
// Ensure the heap exists
uint256 heapLength = _heap.entries.length;
require(heapLength > 1, "The heap does not exists");
// take the root value of the heap
(_addr, _value) = decode(_heap.entries[1]);
_heap.index[_addr] = 0;
if (heapLength == 2) {
_heap.entries.length = 1;
} else {
// Takes the last element of the array and put it at the root
uint256 val = _heap.entries[heapLength - 1];
_heap.entries[1] = val;
// Delete the last element from the array
_heap.entries.length = heapLength - 1;
// Start at the top
uint256 ind = 1;
// Bubble down
ind = _heap.bubbleDown(ind, val);
// Update index
_heap.index[decodeAddress(val)] = ind;
}
}
// Inserts adds in a value to our heap.
function insert(Heap storage _heap, address _addr, uint256 _value) internal {
require(_heap.index[_addr] == 0, "The entry already exists");
// Add the value to the end of our array
uint256 encoded = encode(_addr, _value);
_heap.entries.push(encoded);
// Start at the end of the array
uint256 currentIndex = _heap.entries.length - 1;
// Bubble Up
currentIndex = _heap.bubbleUp(currentIndex, encoded);
// Update index
_heap.index[_addr] = currentIndex;
}
function update(Heap storage _heap, address _addr, uint256 _value) internal {
uint256 ind = _heap.index[_addr];
require(ind != 0, "The entry does not exists");
uint256 can = encode(_addr, _value);
uint256 val = _heap.entries[ind];
uint256 newInd;
if (can < val) {
// Bubble down
newInd = _heap.bubbleDown(ind, can);
} else if (can > val) {
// Bubble up
newInd = _heap.bubbleUp(ind, can);
} else {
// no changes needed
return;
}
// Update entry
_heap.entries[newInd] = can;
// Update index
if (newInd != ind) {
_heap.index[_addr] = newInd;
}
}
function bubbleUp(Heap storage _heap, uint256 _ind, uint256 _val) internal returns (uint256 ind) {
// Bubble up
ind = _ind;
if (ind != 1) {
uint256 parent = _heap.entries[ind / 2];
while (parent < _val) {
// If the parent value is lower than our current value, we swap them
(_heap.entries[ind / 2], _heap.entries[ind]) = (_val, parent);
// Update moved Index
_heap.index[decodeAddress(parent)] = ind;
// change our current Index to go up to the parent
ind = ind / 2;
if (ind == 1) {
break;
}
// Update parent
parent = _heap.entries[ind / 2];
}
}
}
function bubbleDown(Heap storage _heap, uint256 _ind, uint256 _val) internal returns (uint256 ind) {
// Bubble down
ind = _ind;
uint256 lenght = _heap.entries.length;
uint256 target = lenght - 1;
while (ind * 2 < lenght) {
// get the current index of the children
uint256 j = ind * 2;
// left child value
uint256 leftChild = _heap.entries[j];
// Store the value of the child
uint256 childValue;
if (target > j) {
// The parent has two childs 👨👧👦
// Load right child value
uint256 rightChild = _heap.entries[j + 1];
// Compare the left and right child.
// if the rightChild is greater, then point j to it's index
// and save the value
if (leftChild < rightChild) {
childValue = rightChild;
j = j + 1;
} else {
// The left child is greater
childValue = leftChild;
}
} else {
// The parent has a single child 👨👦
childValue = leftChild;
}
// Check if the child has a lower value
if (_val > childValue) {
break;
}
// else swap the value
(_heap.entries[ind], _heap.entries[j]) = (childValue, _val);
// Update moved Index
_heap.index[decodeAddress(childValue)] = ind;
// and let's keep going down the heap
ind = j;
}
}
}
// File: contracts/Heap.sol
pragma solidity ^0.5.10;
contract Heap is Ownable {
using AddressMinHeap for AddressMinHeap.Heap;
// heap
AddressMinHeap.Heap private heap;
// Heap events
event JoinHeap(address indexed _address, uint256 _balance, uint256 _prevSize);
event LeaveHeap(address indexed _address, uint256 _balance, uint256 _prevSize);
uint256 public constant TOP_SIZE = 512;
constructor() public {
heap.initialize();
}
function topSize() external pure returns (uint256) {
return TOP_SIZE;
}
function addressAt(uint256 _i) external view returns (address addr) {
(addr, ) = heap.entry(_i);
}
function indexOf(address _addr) external view returns (uint256) {
return heap.index[_addr];
}
function entry(uint256 _i) external view returns (address, uint256) {
return heap.entry(_i);
}
function top() external view returns (address, uint256) {
return heap.top();
}
function size() external view returns (uint256) {
return heap.size();
}
function update(address _addr, uint256 _new) external onlyOwner {
uint256 _size = heap.size();
// If the heap is empty
// join the _addr
if (_size == 0) {
emit JoinHeap(_addr, _new, 0);
heap.insert(_addr, _new);
return;
}
// Load top value of the heap
(, uint256 lastBal) = heap.top();
// If our target address already is in the heap
if (heap.has(_addr)) {
// Update the target address value
heap.update(_addr, _new);
// If the new value is 0
// always pop the heap
// we updated the heap, so our address should be on top
if (_new == 0) {
heap.popTop();
emit LeaveHeap(_addr, 0, _size);
}
} else {
// IF heap is full or new balance is higher than pop heap
if (_new != 0 && (_size < TOP_SIZE || lastBal < _new)) {
// If heap is full pop heap
if (_size >= TOP_SIZE) {
(address _poped, uint256 _balance) = heap.popTop();
emit LeaveHeap(_poped, _balance, _size);
}
// Insert new value
heap.insert(_addr, _new);
emit JoinHeap(_addr, _new, _size);
}
}
}
}
// File: contracts/ShuffleToken.sol
pragma solidity ^0.5.10;
contract ShuffleToken is Ownable, GasPump, IERC20 {
using DistributedStorage for bytes32;
using SafeMath for uint256;
// Shuffle events
event Winner(address indexed _addr, uint256 _value);
// Managment events
event SetName(string _prev, string _new);
event SetExtraGas(uint256 _prev, uint256 _new);
event SetHeap(address _prev, address _new);
event WhitelistFrom(address _addr, bool _whitelisted);
event WhitelistTo(address _addr, bool _whitelisted);
uint256 public totalSupply;
bytes32 private constant BALANCE_KEY = keccak256("balance");
// game
uint256 public constant FEE = 100;
// metadata
string public name = "Shuffle.Monster V3";
string public constant symbol = "SHUF";
uint8 public constant decimals = 18;
// fee whitelist
mapping(address => bool) public whitelistFrom;
mapping(address => bool) public whitelistTo;
// heap
Heap public heap;
// internal
uint256 public extraGas;
bool inited;
function init(
address _to,
uint256 _amount
) external {
// Only init once
assert(!inited);
inited = true;
// Sanity checks
assert(totalSupply == 0);
assert(address(heap) == address(0));
// Create Heap
heap = new Heap();
emit SetHeap(address(0), address(heap));
// Init contract variables and mint
// entire token balance
extraGas = 15;
emit SetExtraGas(0, extraGas);
emit Transfer(address(0), _to, _amount);
_setBalance(_to, _amount);
totalSupply = _amount;
}
///
// Storage access functions
///
// Getters
function _toKey(address a) internal pure returns (bytes32) {
return bytes32(uint256(a));
}
function _balanceOf(address _addr) internal view returns (uint256) {
return uint256(_toKey(_addr).read(BALANCE_KEY));
}
function _allowance(address _addr, address _spender) internal view returns (uint256) {
return uint256(_toKey(_addr).read(keccak256(abi.encodePacked("allowance", _spender))));
}
function _nonce(address _addr, uint256 _cat) internal view returns (uint256) {
return uint256(_toKey(_addr).read(keccak256(abi.encodePacked("nonce", _cat))));
}
// Setters
function _setAllowance(address _addr, address _spender, uint256 _value) internal {
_toKey(_addr).write(keccak256(abi.encodePacked("allowance", _spender)), bytes32(_value));
}
function _setNonce(address _addr, uint256 _cat, uint256 _value) internal {
_toKey(_addr).write(keccak256(abi.encodePacked("nonce", _cat)), bytes32(_value));
}
function _setBalance(address _addr, uint256 _balance) internal {
_toKey(_addr).write(BALANCE_KEY, bytes32(_balance));
heap.update(_addr, _balance);
}
///
// Internal methods
///
function _isWhitelisted(address _from, address _to) internal view returns (bool) {
return whitelistFrom[_from]||whitelistTo[_to];
}
function _random(address _s1, uint256 _s2, uint256 _s3, uint256 _max) internal pure returns (uint256) {
uint256 rand = uint256(keccak256(abi.encodePacked(_s1, _s2, _s3)));
return rand % (_max + 1);
}
function _pickWinner(address _from, uint256 _value) internal returns (address winner) {
// Get order of magnitude of the tx
uint256 magnitude = Math.orderOfMagnitude(_value);
// Pull nonce for a given order of magnitude
uint256 nonce = _nonce(_from, magnitude);
_setNonce(_from, magnitude, nonce + 1);
// pick entry from heap
winner = heap.addressAt(_random(_from, nonce, magnitude, heap.size() - 1));
}
function _transferFrom(address _operator, address _from, address _to, uint256 _value, bool _payFee) internal {
// If transfer amount is zero
// emit event and stop execution
if (_value == 0) {
emit Transfer(_from, _to, 0);
return;
}
// Load sender balance
uint256 balanceFrom = _balanceOf(_from);
require(balanceFrom >= _value, "balance not enough");
// Check if operator is sender
if (_from != _operator) {
// If not, validate allowance
uint256 allowanceFrom = _allowance(_from, _operator);
// If allowance is not 2 ** 256 - 1, consume allowance
if (allowanceFrom != uint(-1)) {
// Check allowance and save new one
require(allowanceFrom >= _value, "allowance not enough");
_setAllowance(_from, _operator, allowanceFrom.sub(_value));
}
}
// Calculate receiver balance
// initial receive is full value
uint256 receive = _value;
uint256 burn = 0;
uint256 shuf = 0;
// Change sender balance
_setBalance(_from, balanceFrom.sub(_value));
// If the transaction is not whitelisted
// or if sender requested to pay the fee
// calculate fees
if (_payFee || !_isWhitelisted(_from, _to)) {
// Fee is the same for BURN and SHUF
// If we are sending value one
// give priority to BURN
burn = _value.divRound(FEE);
shuf = _value == 1 ? 0 : burn;
// Subtract fees from receiver amount
receive = receive.sub(burn.add(shuf));
// Burn tokens
totalSupply = totalSupply.sub(burn);
emit Transfer(_from, address(0), burn);
// Shuffle tokens
// Pick winner pseudo-randomly
address winner = _pickWinner(_from, _value);
// Transfer balance to winner
_setBalance(winner, _balanceOf(winner).add(shuf));
emit Winner(winner, shuf);
emit Transfer(_from, winner, shuf);
}
// Sanity checks
// no tokens where created
assert(burn.add(shuf).add(receive) == _value);
// Add tokens to receiver
_setBalance(_to, _balanceOf(_to).add(receive));
emit Transfer(_from, _to, receive);
}
///
// Managment
///
function setWhitelistedTo(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistTo(_addr, _whitelisted);
whitelistTo[_addr] = _whitelisted;
}
function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistFrom(_addr, _whitelisted);
whitelistFrom[_addr] = _whitelisted;
}
function setName(string calldata _name) external onlyOwner {
emit SetName(name, _name);
name = _name;
}
function setExtraGas(uint256 _gas) external onlyOwner {
emit SetExtraGas(extraGas, _gas);
extraGas = _gas;
}
function setHeap(Heap _heap) external onlyOwner {
emit SetHeap(address(heap), address(_heap));
heap = _heap;
}
/////
// Heap methods
/////
function topSize() external view returns (uint256) {
return heap.topSize();
}
function heapSize() external view returns (uint256) {
return heap.size();
}
function heapEntry(uint256 _i) external view returns (address, uint256) {
return heap.entry(_i);
}
function heapTop() external view returns (address, uint256) {
return heap.top();
}
function heapIndex(address _addr) external view returns (uint256) {
return heap.indexOf(_addr);
}
function getNonce(address _addr, uint256 _cat) external view returns (uint256) {
return _nonce(_addr, _cat);
}
/////
// ERC20
/////
function balanceOf(address _addr) external view returns (uint256) {
return _balanceOf(_addr);
}
function allowance(address _addr, address _spender) external view returns (uint256) {
return _allowance(_addr, _spender);
}
function approve(address _spender, uint256 _value) external returns (bool) {
emit Approval(msg.sender, _spender, _value);
_setAllowance(msg.sender, _spender, _value);
return true;
}
function transfer(address _to, uint256 _value) external requestGas(extraGas) returns (bool) {
_transferFrom(msg.sender, msg.sender, _to, _value, false);
return true;
}
function transferWithFee(address _to, uint256 _value) external requestGas(extraGas) returns (bool) {
_transferFrom(msg.sender, msg.sender, _to, _value, true);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) external requestGas(extraGas) returns (bool) {
_transferFrom(msg.sender, _from, _to, _value, false);
return true;
}
function transferFromWithFee(address _from, address _to, uint256 _value) external requestGas(extraGas) returns (bool) {
_transferFrom(msg.sender, _from, _to, _value, true);
return true;
}
}
// File: contracts/utils/SigUtils.sol
pragma solidity ^0.5.10;
library SigUtils {
/**
@dev Recovers address who signed the message
@param _hash operation ethereum signed message hash
@param _signature message `hash` signature
*/
function ecrecover2(
bytes32 _hash,
bytes memory _signature
) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
/* solium-disable-next-line */
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := and(mload(add(_signature, 65)), 255)
}
if (v < 27) {
v += 27;
}
return ecrecover(
_hash,
v,
r,
s
);
}
}
// File: contracts/utils/SafeCast.sol
pragma solidity ^0.5.10;
library SafeCast {
function toUint96(uint256 _a) internal pure returns (uint96) {
require(_a <= 2 ** 96 - 1, "cast uint96 overflow");
return uint96(_a);
}
}
// File: contracts/Airdrop.sol
pragma solidity ^0.5.10;
contract Airdrop is Ownable, ReentrancyGuard {
using IsContract for address payable;
using SafeCast for uint256;
using SafeMath for uint256;
ShuffleToken public shuffleToken;
// Managment
uint64 public maxClaimedBy = 0;
uint256 public refsCut;
mapping(address => uint256) public customMaxClaimedBy;
bool public paused;
event SetMaxClaimedBy(uint256 _max);
event SetCustomMaxClaimedBy(address _address, uint256 _max);
event SetSigner(address _signer, bool _active);
event SetMigrator(address _migrator, bool _active);
event SetFuse(address _fuse, bool _active);
event SetPaused(bool _paused);
event SetRefsCut(uint256 _prev, uint256 _new);
event Claimed(address _by, address _to, address _signer, uint256 _value, uint256 _claimed);
event RefClaim(address _ref, uint256 _val);
event ClaimedOwner(address _owner, uint256 _tokens);
uint256 public constant MINT_AMOUNT = 1000000 * 10 ** 18;
uint256 public constant SHUFLE_BY_ETH = 150;
uint256 public constant MAX_CLAIM_ETH = 10 ether;
mapping(address => bool) public isSigner;
mapping(address => bool) public isMigrator;
mapping(address => bool) public isFuse;
mapping(address => uint256) public claimed;
mapping(address => uint256) public numberClaimedBy;
constructor(ShuffleToken _token) public {
shuffleToken = _token;
shuffleToken.init(address(this), MINT_AMOUNT);
emit SetMaxClaimedBy(maxClaimedBy);
}
// ///
// Managment
// ///
modifier notPaused() {
require(!paused, "contract is paused");
_;
}
function setMaxClaimedBy(uint64 _max) external onlyOwner {
maxClaimedBy = _max;
emit SetMaxClaimedBy(_max);
}
function setSigner(address _signer, bool _active) external onlyOwner {
isSigner[_signer] = _active;
emit SetSigner(_signer, _active);
}
function setMigrator(address _migrator, bool _active) external onlyOwner {
isMigrator[_migrator] = _active;
emit SetMigrator(_migrator, _active);
}
function setFuse(address _fuse, bool _active) external onlyOwner {
isFuse[_fuse] = _active;
emit SetFuse(_fuse, _active);
}
function setSigners(address[] calldata _signers, bool _active) external onlyOwner {
for (uint256 i = 0; i < _signers.length; i++) {
address signer = _signers[i];
isSigner[signer] = _active;
emit SetSigner(signer, _active);
}
}
function setCustomMaxClaimedBy(address _address, uint256 _max) external onlyOwner {
customMaxClaimedBy[_address] = _max;
emit SetCustomMaxClaimedBy(_address, _max);
}
function setRefsCut(uint256 _val) external onlyOwner {
emit SetRefsCut(refsCut, _val);
refsCut = _val;
}
function pause() external {
require(
isFuse[msg.sender] ||
msg.sender == owner ||
isMigrator[msg.sender] ||
isSigner[msg.sender],
"not authorized"
);
paused = true;
emit SetPaused(true);
}
function start() external onlyOwner {
emit SetPaused(false);
paused = false;
}
// ///
// Airdrop
// ///
function _selfBalance() internal view returns (uint256) {
return shuffleToken.balanceOf(address(this));
}
function checkFallback(address _to) private returns (bool success) {
/* solium-disable-next-line */
(success, ) = _to.call.value(1)("");
}
function claim(
address _to,
address _ref,
uint256 _val,
bytes calldata _sig
) external notPaused nonReentrant {
// Load values
uint96 val = _val.toUint96();
// Validate signature
bytes32 _hash = keccak256(abi.encodePacked(_to, val));
address signer = SigUtils.ecrecover2(_hash, _sig);
require(isSigner[signer], "signature not valid");
// Prepare claim amount
uint256 balance = _selfBalance();
uint256 claimVal = Math.min(
balance,
Math.min(
val,
MAX_CLAIM_ETH
).mult(SHUFLE_BY_ETH)
);
// Sanity checks
assert(claimVal <= SHUFLE_BY_ETH.mult(val));
assert(claimVal <= MAX_CLAIM_ETH.mult(SHUFLE_BY_ETH));
assert(claimVal.div(SHUFLE_BY_ETH) <= MAX_CLAIM_ETH);
assert(
claimVal.div(SHUFLE_BY_ETH) == _val ||
claimVal.div(SHUFLE_BY_ETH) == MAX_CLAIM_ETH ||
claimVal == balance
);
// Claim, only once
require(claimed[_to] == 0, "already claimed");
claimed[_to] = claimVal;
// External claim checks
if (msg.sender != _to) {
// Validate max external claims
uint256 _numberClaimedBy = numberClaimedBy[msg.sender].add(1);
require(_numberClaimedBy <= Math.max(maxClaimedBy, customMaxClaimedBy[msg.sender]), "max claim reached");
numberClaimedBy[msg.sender] = _numberClaimedBy;
// Check if _to address can receive ETH
require(checkFallback(_to), "_to address can't receive tokens");
}
// Transfer Shuffle token, paying fee
shuffleToken.transferWithFee(_to, claimVal);
// Emit events
emit Claimed(msg.sender, _to, signer, val, claimVal);
// Ref links
if (refsCut != 0) {
// Only valid for self-claims
if (msg.sender == _to && _ref != address(0)) {
// Calc transfer extra
uint256 extra = claimVal.mult(refsCut).div(10000);
// Ignore ref fee if Airdrop balance is not enought
if (_selfBalance() >= extra) {
shuffleToken.transferWithFee(_ref, extra);
emit RefClaim(_ref, extra);
// Sanity checks
assert(extra <= MAX_CLAIM_ETH.mult(SHUFLE_BY_ETH));
assert(extra <= claimVal);
assert(extra == (claimVal * refsCut) / 10000);
}
}
}
// If contract is empty, perform self destruct
if (balance == claimVal && _selfBalance() == 0) {
selfdestruct(address(uint256(owner)));
}
}
// Migration methods
event Migrated(address _addr, uint256 _balance);
mapping(address => uint256) public migrated;
function migrate(address _addr, uint256 _balance, uint256 _require) external notPaused {
// Check if migrator is a migrator
require(isMigrator[msg.sender], "only migrator can migrate");
// Check if expected migrated matches current migrated
require(migrated[_addr] == _require, "_require prev migrate failed");
// Save migrated amount
migrated[_addr] = migrated[_addr].add(_balance);
// Transfer tokens and emit event
shuffleToken.transfer(_addr, _balance);
emit Migrated(_addr, _balance);
}
function fund() external payable { }
} | solium-disable-next-line / | function decode(uint256 _entry) internal pure returns (address _addr, uint256 _value) {
assembly {
let entry := not(_entry)
_addr := and(entry, 0xffffffffffffffffffffffffffffffffffffffff)
_value := shr(160, entry)
}
}
| 881,550 |
./full_match/1/0xFf856fEc08C45e02941c66cf73dC269F90878e76/sources/contracts/PunkMe.sol | Allows to mint NFTs/ | function mint() external payable {
}
| 9,619,428 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MockZHegic.sol";
/**
* @dev To simulate the floating conversion rate of zHEGIC/HEGIC, here we start
* with 1:1, then increase a preset percentage per block. e.g. One blocks after
* the contract is created, 1 zHEGIC will worth 1.05 HEGIC; another block after
* that, 1 zHEGIC will worth 1.10 HEGIC, etc.
*/
contract MockZLotPool is Ownable {
using SafeMath for uint;
using SafeERC20 for ERC20;
ERC20 public immutable HEGIC;
MockZHegic public immutable zHEGIC;
uint public start;
uint rateIncreasePerBlock;
constructor(ERC20 _HEGIC, MockZHegic _zHEGIC, uint _rateIncreasePerBlock) {
HEGIC = _HEGIC;
zHEGIC = _zHEGIC;
start = block.number;
rateIncreasePerBlock = _rateIncreasePerBlock;
}
/**
* @dev Reset the start block to the current block. Added this function so I
* can reuse the same contract instances for multiple tests. Same goes for `setRateIncrease`.
*/
function resetStartBlock() external onlyOwner {
start = block.number;
}
function setRateIncrease(uint _rateIncreasePerBlock) external onlyOwner {
rateIncreasePerBlock = _rateIncreasePerBlock;
}
function deposit(uint amount) external returns (uint zTokenAmount) {
uint blocksPassed = (block.number).sub(start);
zTokenAmount = amount.mul(100).div(blocksPassed.mul(rateIncreasePerBlock).add(100));
HEGIC.safeTransferFrom(msg.sender, address(this), amount);
zHEGIC.mint(msg.sender, zTokenAmount);
}
}
| Reset the start block to the current block. Added this function so I can reuse the same contract instances for multiple tests. Same goes for `setRateIncrease`./ | function resetStartBlock() external onlyOwner {
start = block.number;
}
| 13,092,926 |
./full_match/1/0xCd000DF47446cfd7D660aDEb4021B710AA41DeD9/sources/src/GreyMarket.sol | Claim multiple orders. Claim multiple orders. ids Order ids buyers The addresses of the buyers sellers The addresses of the sellers sigs Array of ECDSA signatures/ | function claimOrders(
bytes32[] calldata ids,
address[] calldata buyers,
address[] calldata sellers,
Sig[] calldata sigs
) external {
require(sigs.length == ids.length, "invalid length");
require(sellers.length == buyers.length, "invalid length");
uint256 len = ids.length;
uint256 i;
unchecked {
do {
claimOrder(ids[i], buyers[i], sellers[i], sigs[i]);
} while(++i < len);
}
}
| 16,609,966 |
pragma solidity ^0.4.24;
import "./Plugin.sol";
import "./interfaces/ENSInterface.sol";
import "./interfaces/PliTokenInterface.sol";
import "./interfaces/PluginRequestInterface.sol";
import "./interfaces/PointerInterface.sol";
import { ENSResolver as ENSResolver_Plugin } from "./vendor/ENSResolver.sol";
/**
* @title The PluginClient contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Plugin network
*/
contract PluginClient {
using Plugin for Plugin.Request;
uint256 constant internal PLI = 10**18;
uint256 constant private AMOUNT_OVERRIDE = 0;
address constant private SENDER_OVERRIDE = 0x0;
uint256 constant private ARGS_VERSION = 1;
bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("pli");
bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle");
address constant private PLI_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private ens;
bytes32 private ensNode;
PliTokenInterface private pli;
PluginRequestInterface private oracle;
uint256 private requests = 1;
mapping(bytes32 => address) private pendingRequests;
event PluginRequested(bytes32 indexed id);
event PluginFulfilled(bytes32 indexed id);
event PluginCancelled(bytes32 indexed id);
/**
* @notice Creates a request that can hold additional parameters
* @param _specId The Job Specification ID that the request will be created for
* @param _callbackAddress The callback address that the response will be sent to
* @param _callbackFunctionSignature The callback function signature to use for the callback address
* @return A Plugin Request struct in memory
*/
function buildPluginRequest(
bytes32 _specId,
address _callbackAddress,
bytes4 _callbackFunctionSignature
) internal pure returns (Plugin.Request memory) {
Plugin.Request memory req;
return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature);
}
/**
* @notice Creates a Plugin request to the stored oracle address
* @dev Calls `pluginRequestTo` with the stored oracle address
* @param _req The initialized Plugin Request
* @param _payment The amount of PLI to send for the request
* @return The request ID
*/
function sendPluginRequest(Plugin.Request memory _req, uint256 _payment)
internal
returns (bytes32)
{
return sendPluginRequestTo(oracle, _req, _payment);
}
/**
* @notice Creates a Plugin request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send PLI which creates a request on the target oracle contract.
* Emits PluginRequested event.
* @param _oracle The address of the oracle for the request
* @param _req The initialized Plugin Request
* @param _payment The amount of PLI to send for the request
* @return The request ID
*/
function sendPluginRequestTo(address _oracle, Plugin.Request memory _req, uint256 _payment)
internal
returns (bytes32 requestId)
{
requestId = keccak256(abi.encodePacked(this, requests));
_req.nonce = requests;
pendingRequests[requestId] = _oracle;
emit PluginRequested(requestId);
require(pli.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle");
requests += 1;
return requestId;
}
/**
* @notice Allows a request to be cancelled if it has not been fulfilled
* @dev Requires keeping track of the expiration value emitted from the oracle contract.
* Deletes the request from the `pendingRequests` mapping.
* Emits PluginCancelled event.
* @param _requestId The request ID
* @param _payment The amount of PLI sent for the request
* @param _callbackFunc The callback function specified for the request
* @param _expiration The time of the expiration for the request
*/
function cancelPluginRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunc,
uint256 _expiration
)
internal
{
PluginRequestInterface requested = PluginRequestInterface(pendingRequests[_requestId]);
delete pendingRequests[_requestId];
emit PluginCancelled(_requestId);
requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration);
}
/**
* @notice Sets the stored oracle address
* @param _oracle The address of the oracle contract
*/
function setPluginOracle(address _oracle) internal {
oracle = PluginRequestInterface(_oracle);
}
/**
* @notice Sets the PLI token address
* @param _pli The address of the PLI token contract
*/
function setPluginToken(address _pli) internal {
pli = PliTokenInterface(_pli);
}
/**
* @notice Sets the Plugin token address for the public
* network as given by the Pointer contract
*/
function setPublicPluginToken() internal {
setPluginToken(PointerInterface(PLI_TOKEN_POINTER).getAddress());
}
/**
* @notice Retrieves the stored address of the PLI token
* @return The address of the PLI token
*/
function pluginTokenAddress()
internal
view
returns (address)
{
return address(pli);
}
/**
* @notice Retrieves the stored address of the oracle contract
* @return The address of the oracle contract
*/
function pluginOracleAddress()
internal
view
returns (address)
{
return address(oracle);
}
/**
* @notice Allows for a request which was created on another contract to be fulfilled
* on this contract
* @param _oracle The address of the oracle contract that will fulfill the request
* @param _requestId The request ID used for the response
*/
function addPluginExternalRequest(address _oracle, bytes32 _requestId)
internal
notPendingRequest(_requestId)
{
pendingRequests[_requestId] = _oracle;
}
/**
* @notice Sets the stored oracle and PLI token contracts with the addresses resolved by ENS
* @dev Accounts for subnodes having different resolvers
* @param _ens The address of the ENS contract
* @param _node The ENS node hash
*/
function usePluginWithENS(address _ens, bytes32 _node)
internal
{
ens = ENSInterface(_ens);
ensNode = _node;
bytes32 pliSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
ENSResolver_Plugin resolver = ENSResolver_Plugin(ens.resolver(pliSubnode));
setPluginToken(resolver.addr(pliSubnode));
updatePluginOracleWithENS();
}
/**
* @notice Sets the stored oracle contract with the address resolved by ENS
* @dev This may be called on its own as long as `usePluginWithENS` has been called previously
*/
function updatePluginOracleWithENS()
internal
{
bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME));
ENSResolver_Plugin resolver = ENSResolver_Plugin(ens.resolver(oracleSubnode));
setPluginOracle(resolver.addr(oracleSubnode));
}
/**
* @notice Encodes the request to be sent to the oracle contract
* @dev The Plugin node expects values to be in order for the request to be picked up. Order of types
* will be validated in the oracle contract.
* @param _req The initialized Plugin Request
* @return The bytes payload for the `transferAndCall` method
*/
function encodeRequest(Plugin.Request memory _req)
private
view
returns (bytes memory)
{
return abi.encodeWithSelector(
oracle.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of PLI sent
_req.id,
_req.callbackAddress,
_req.callbackFunctionId,
_req.nonce,
ARGS_VERSION,
_req.buf.buf);
}
/**
* @notice Ensures that the fulfillment is valid for this contract
* @dev Use if the contract developer prefers methods instead of modifiers for validation
* @param _requestId The request ID for fulfillment
*/
function validatePluginCallback(bytes32 _requestId)
internal
recordPluginFulfillment(_requestId)
// solhint-disable-next-line no-empty-blocks
{}
/**
* @dev Reverts if the sender is not the oracle of the request.
* Emits PluginFulfilled event.
* @param _requestId The request ID for fulfillment
*/
modifier recordPluginFulfillment(bytes32 _requestId) {
require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request");
delete pendingRequests[_requestId];
emit PluginFulfilled(_requestId);
_;
}
/**
* @dev Reverts if the request is already pending
* @param _requestId The request ID for fulfillment
*/
modifier notPendingRequest(bytes32 _requestId) {
require(pendingRequests[_requestId] == address(0), "Request is already pending");
_;
}
}
| Sets the PLI token address _pli The address of the PLI token contract/ | function setPluginToken(address _pli) internal {
pli = PliTokenInterface(_pli);
}
| 1,802,456 |
pragma solidity ^0.5.0;
// Ownable.sol
import "installed_contracts/zeppelin/contracts/ownership/Ownable.sol";
/* Contact used for football competitions */
contract FootballCompetition is Ownable {
/* football competition */
/* for the purposes of the problem only 255 competitions can be added to this contract */
struct Competition {
uint8 id; // competition id
string name; // name for competition
address organizer; // the address organizing the competition
bool created; // is competition created
uint potBalance; // total balance in competition
uint256 startTimestamp; // competition start timestamp
uint256 winnerTimestamp; // competition winner announcement timestamp
bool winnerAnnounced; // is the winner announced
uint8 winningTeam; // the winning team
uint8[] teamIds; // holds a list of team ids
uint8 totalTeams; // total number of teams
mapping(uint8 => bool) teams; // teams available in competition
mapping(uint8 => uint) betsOnTeam; // total bets on a team
mapping(address => Participant) participants; // the participants in the competition
}
/* struct for team */
struct Team {
uint8 id; // team id
string name; // team name
bool nameSet; // is team name set
}
/* struct for participant */
struct Participant {
uint8 teamId; // team betting on
bool isCompeting; // is participant competing
}
/* holds count of the total competitions */
uint8 private competitionCount;
/* the maximum competitions which can be added */
uint8 constant maxCompetitions = 255;
/* the maximum football teams which can be added */
uint8 constant maxFootballTeams = 255;
/* holds count of the total teams */
uint8 private teamCount;
/* holds football teams which can be found in any competition */
/* for the purposes of the problem only 255 teams can be added to this contract */
mapping(uint8 => Team) private footballTeams;
/* holds a mapping of available competitions */
/* for the purposes of the problem only 255 competitions can be added to this contract */
mapping(uint8 => Competition) private competitions;
/* this constructor is executed at initialization and sets the owner of the contract */
constructor() public {
competitionCount = 0; // set number of competitions to 0
teamCount = 0; // set number of teams to 0
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOrganizer(uint8 competitionId) {
require(isOrganizer(competitionId), "Not Organizer.");
_;
}
/**
* @return true if `msg.sender` is the organizer of the competition.
*/
function isOrganizer(uint8 competitionId) public view returns (bool) {
return msg.sender == competitions[competitionId].organizer;
}
/**
* @dev Throws if competition does not exist.
*/
modifier competitionExist(uint8 competitionId) {
require(competitions[competitionId].created == true, "Competition does not exist.");
_;
}
/**
* @dev Throws if team does not exist.
*/
modifier teamExist(uint8 teamId) {
require(footballTeams[teamId].nameSet == true, "Team does not exist.");
_;
}
/**
* @dev Throws if called competition already started.
*/
modifier competitionStarted(uint8 competitionId) {
require(now < competitions[competitionId].startTimestamp, "Competition already started.");
_;
}
/**
* @dev Throws if team is not in competition.
*/
modifier teamInCompetition(uint8 competitionId, uint8 teamId) {
require(competitions[competitionId].teams[teamId] == true, "Team is not available in competition");
_;
}
/* returns the total number of teams */
function getTeamCount() public view returns (uint8) {
return teamCount;
}
/* returns the total number of competitions */
function getCompetitionCount() public view returns (uint8) {
return competitionCount;
}
/* add a new team to this contract (only the one who deployed contract can add team) */
/* these teams can be used in a specific competition */
/* this insures transparency as it cant be edited and the participant */
/* is insured that team with a specific id is the team with a specific name */
function addTeam(string memory name) public onlyOwner() {
// check if more teams can be added to this contract
require(teamCount < maxFootballTeams, "Cannot add more teams.");
// increment before as we dont want id 0 to be a team
teamCount += 1;
// adds a new team
footballTeams[teamCount] = Team(teamCount, name, true);
}
// get team name for the specified id
function getTeam(uint8 id) public view teamExist(id) returns(
uint8,
string
memory
)
{
// return team information
return (footballTeams[id].id, footballTeams[id].name);
}
/* add a new competition (anyone can start a competition) */
function addCompetition(
string memory name, // name of competition
uint256 startTimestamp, // competition starting date
uint256 winnerTimestamp // competition winner announcement date
)
public
{
// check if more competitions can be added to this contract
require(competitionCount < maxCompetitions, "Cannot add more competitions.");
// check dates
require(now <= startTimestamp, "Invalid start date.");
require(startTimestamp < winnerTimestamp, "Invalid winner date.");
// increment before as we dont want id 0 to be a competition
competitionCount += 1;
// set values for new competition
Competition memory newCompetition;
newCompetition.id = competitionCount;
newCompetition.name = name;
newCompetition.organizer = msg.sender;
newCompetition.created = true;
newCompetition.potBalance = 0;
newCompetition.startTimestamp = startTimestamp;
newCompetition.winnerTimestamp = winnerTimestamp;
newCompetition.winnerAnnounced = false;
newCompetition.teamIds = new uint8[](255);
newCompetition.totalTeams = 0;
// add competition
competitions[competitionCount] = newCompetition;
}
/* return details about a competition */
function getCompetition(uint8 id) public view competitionExist(id) returns (
uint8, // competition id
string memory, // competition name
address, // organizer
uint, // pot balance
uint256, // start ts
uint256, // end timestamp
bool, // winner announced
uint8, // winning team
uint8[] memory, // team ids
uint8 // total teams
)
{
Competition memory tmpCompetition = competitions[id];
return(
tmpCompetition.id,
tmpCompetition.name,
tmpCompetition.organizer,
tmpCompetition.potBalance,
tmpCompetition.startTimestamp,
tmpCompetition.winnerTimestamp,
tmpCompetition.winnerAnnounced,
tmpCompetition.winningTeam,
tmpCompetition.teamIds,
tmpCompetition.totalTeams
);
}
/* teams to be added in a competition must be entered one by one */
/* this is because of the problems of evm and unbounded loops */
/* only accessible by organizer */
function addTeamToCompetition(
uint8 competitionId, // the competition id to add new team
uint8 teamId // the team which will be added to the competition
)
public
onlyOrganizer(competitionId) // only accessible by organizer
teamExist(teamId) // check if team exist
competitionExist(competitionId) // check if competition exist
competitionStarted(competitionId) // check if competition started
{
// check if team exists
require(footballTeams[teamId].nameSet == true, "Team does not exist");
// check if team is already in competition (cannot override teams!)
require(competitions[competitionId].teams[teamId] == false, "Team already in competition.");
// add team to competition
competitions[competitionId].teams[teamId] = true;
// increment total number of teams in competition and add team to competition
competitions[competitionId].teamIds[competitions[competitionId].totalTeams] = teamId;
competitions[competitionId].totalTeams += 1;
}
/* allows participants to join a specific competition */
function joinCompetition(
uint8 competitionId, // competion id which the address will be joining
uint8 teamId // the team id which the address is betting on
)
public
competitionExist(competitionId) // check if competition exist
competitionStarted(competitionId) // check if competition started
teamInCompetition(competitionId, teamId) // check if team is available in competition
{
// check if the one joining is already in competition (one address one bet)
require(competitions[competitionId].participants[msg.sender].isCompeting == false, "Already in competition.");
// set new balance for pot
competitions[competitionId].potBalance += 10;
// set team for participant
competitions[competitionId].participants[msg.sender].isCompeting = true;
competitions[competitionId].participants[msg.sender].teamId = teamId;
// increment the number of bets on that team
competitions[competitionId].betsOnTeam[teamId] += 1;
}
/* set winner for a specific competition only accessible by organizer */
function setWinningTeam(
uint8 competitionId, // the competition id to set the winner for
uint8 teamId // the winning team for the competition
)
public
onlyOrganizer(competitionId) // only accessed by organizer
competitionExist(competitionId) // check if competition exist
teamInCompetition(competitionId, teamId) // check if team is available in competition
{
// cannot override winner check if winner was already announced
require(competitions[competitionId].winnerAnnounced == false, "Winner is already set.");
// can set winner if competition is over
require(now >= competitions[competitionId].winnerTimestamp, "Competition not finished yet.");
// set winning team
competitions[competitionId].winnerAnnounced = true;
competitions[competitionId].winningTeam = teamId;
}
/* check winnings for a participant */
function checkWinnings(uint8 competitionId) public view competitionExist(competitionId) returns(
bool,
uint,
uint,
uint,
uint8
)
{
// check if participant was actually competing in competition
require(competitions[competitionId].participants[msg.sender].isCompeting == true, "Address was not in competition.");
// check that the winner was announced
require(competitions[competitionId].winnerAnnounced == true, "Winning team not set yet.");
// get competition
Competition storage tmpCompetition = competitions[competitionId];
uint8 winningTeam = tmpCompetition.winningTeam;
uint8 selectedTeam = tmpCompetition.participants[msg.sender].teamId;
bool isWinner = selectedTeam == winningTeam;
uint potBalance = tmpCompetition.potBalance;
uint totalWinners = tmpCompetition.betsOnTeam[winningTeam];
// calculate winnings for the one requesting
uint winnings = 0;
if(isWinner == true){
if(totalWinners > 1){
winnings = potBalance / totalWinners;
}
else{
winnings = potBalance;
}
}
// return values
return(
isWinner, // is the address a winner
potBalance, // total in pot
winnings, // winnings by address
totalWinners, // total winners
selectedTeam // the selected team
);
}
} | teams to be added in a competition must be entered one by one / this is because of the problems of evm and unbounded loops / only accessible by organizer / check if team exists check if team is already in competition (cannot override teams!) add team to competition increment total number of teams in competition and add team to competition | function addTeamToCompetition(
)
public
{
require(footballTeams[teamId].nameSet == true, "Team does not exist");
require(competitions[competitionId].teams[teamId] == false, "Team already in competition.");
competitions[competitionId].teams[teamId] = true;
competitions[competitionId].teamIds[competitions[competitionId].totalTeams] = teamId;
competitions[competitionId].totalTeams += 1;
}
| 12,761,776 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "../SocialTokenNFT/ERC721.sol";
import "../SocialTokenNFT/SizeSortedList.sol";
import "../SocialTokenNFT/ISocialTokenNFT.sol";
import "../SocialTokenNFT/IAuxCompatableNFT.sol";
import "../SocialTokenManager/ISocialTokenManager.sol";
import "../SocialToken/ISocialToken.sol";
contract LongTailSocialNFT is ISocialTokenNFT, IAuxCompatableNFT, ERC721, SizeSortedList {
using Strings for uint256;
ISocialTokenManager public manager;
string[] private baseTokenURIs;
string[] private auxTokenURIs;
bytes32 private immutable AUX_URI_UNLOCK;
uint256 private constant MAXIMUM_LEVEL = 8;
string private SLASH = "/";
string private FORGE_COST = "Forging cost";
string private NOT_ENABLED = "Cannot forge: Not enabled";
mapping(uint256 => NFTData) private dataMap;
mapping(address => uint32[MAXIMUM_LEVEL]) private levelBalances;
mapping(uint256 => GroupData[MAXIMUM_LEVEL - 1]) private groupData; // 1 smaller because level zero isn't represented
mapping(address => NFTData[]) private unclaimedBounties;
uint64[MAXIMUM_LEVEL] private interestBonuses;
uint64 private elementSize;
uint64 private elementIndex;
uint64 public highestDefinedGroup;
address public owner;
uint256 public tokenCount;
int256 private elementMintCost;
int256 private forgeCost;
constructor(address managerAddress, bytes32 auxUriUnlock) ERC721("Long Tail Social NFT", "LTSNFT") {
manager = ISocialTokenManager(managerAddress);
AUX_URI_UNLOCK = auxUriUnlock;
interestBonuses[0] = 70368744177664;
for(uint256 i = 1;i < MAXIMUM_LEVEL;i++) {
interestBonuses[i] = interestBonuses[i - 1] * 3;
}
elementMintCost = -10**19;
owner = _msgSender();
emit OwnershipTransferred(address(0), owner);
}
/**
* Integration functions
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) {
return
interfaceId == type(ISocialTokenNFT).interfaceId ||
interfaceId == type(IAuxCompatableNFT).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* Manager upgrade function
*/
function setManager(address newManager) external {
require(_msgSender() == address(manager));
require(IERC165(newManager).supportsInterface(type(ISocialTokenManager).interfaceId));
manager = ISocialTokenManager(newManager);
}
/**
* Economy adjustment functions
*/
function transferOwnership(address newOwner) public {
manager.authorize(_msgSender(), ISocialTokenManager.Sensitivity.Maintainance);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function setForgeValues(uint256 newElementCost, uint256 newForgeCost, uint64[] memory interestBonusValues) public {
manager.authorize(_msgSender(), ISocialTokenManager.Sensitivity.Maintainance);
elementMintCost = int256(newElementCost) * -1;
forgeCost = int256(newForgeCost) * -1;
for(uint256 i = 0;i < MAXIMUM_LEVEL;i++) {
if (interestBonusValues.length > i && interestBonusValues[i] > 0) {
interestBonuses[i] = interestBonusValues[i];
}
if (i > 0 && interestBonuses[i - 1] > interestBonuses[i]) {
interestBonuses[i] = interestBonuses[i - 1];
}
}
}
function setURIs(uint32 index, string memory newURI, string memory newAuxURI) public {
manager.authorize(_msgSender(), ISocialTokenManager.Sensitivity.Maintainance);
require(index <= baseTokenURIs.length, OUT_OF_BOUNDS);
if (index == baseTokenURIs.length) {
baseTokenURIs.push(newURI);
auxTokenURIs.push(newAuxURI);
}
else {
if (bytes(newURI).length > 0) {
baseTokenURIs[index] = newURI;
}
if (bytes(newAuxURI).length > 0) {
auxTokenURIs[index] = newAuxURI;
}
}
}
/**
* Council functions
*/
function setGroupData(uint64 group, uint64[] memory sizes, bool[] memory auxVersionEnabled, uint32[] memory uriIndexes, uint64[] memory salts) public {
manager.authorize(_msgSender(), ISocialTokenManager.Sensitivity.Council);
require(sizes.length < MAXIMUM_LEVEL, OUT_OF_BOUNDS);
require(sizes.length > 0, OUT_OF_BOUNDS);
require(group <= highestDefinedGroup + 1, OUT_OF_BOUNDS);
if (group == 0) {
emit GroupDataChanged(0, 0, elementSize, sizes[0], 0, false);
elementSize = sizes[0];
if (elementIndex > sizes[0]) {
elementIndex = 0;
}
return;
}
else if(sizes[0] == 0) {
removeItemFromTracking(group);
}
else if (groupData[group][0].size == 0) {
if (group > highestDefinedGroup) {
highestDefinedGroup = group;
}
addItemToTrack(group);
}
GroupData memory thisDatum;
for (uint256 i = 0;i <= sizes.length - 1;i++) {
thisDatum.size = sizes[i];
thisDatum.current = groupData[group][i].current;
if (thisDatum.current > thisDatum.size) {
thisDatum.current = 0;
}
if (uriIndexes.length > i) {
thisDatum.uriIndex = uriIndexes[i];
}
if (auxVersionEnabled.length > i) {
thisDatum.auxEnabled = auxVersionEnabled[i];
}
if (salts.length > i) {
thisDatum.salt = salts[i];
}
if (groupData[group][i].size != thisDatum.size || groupData[group][i].uriIndex != thisDatum.uriIndex ||
groupData[group][i].auxEnabled != thisDatum.auxEnabled) {
emit GroupDataChanged(uint8(i + 2), group, groupData[group][i].size, thisDatum.size, thisDatum.uriIndex, thisDatum.auxEnabled);
}
groupData[group][i] = thisDatum;
}
}
function awardBounty(address recipient, uint256 tokenReward, NFTData[] memory nftAwards) public {
manager.authorize(_msgSender(), ISocialTokenManager.Sensitivity.Council);
require(recipient != address(0));
if (tokenReward > 0) {
manager.getTokenContract().award(recipient, int256(tokenReward), "bounty award");
}
for(uint256 i = 0;i < nftAwards.length;i++) {
unclaimedBounties[recipient].push(nftAwards[i]);
}
emit RewardIssued(recipient, uint128(tokenReward), uint128(nftAwards.length));
}
/**
* Public views
*/
function interestBonus(address account) external view returns(uint64) {
for (uint256 level = MAXIMUM_LEVEL;level > 0;level--) {
if (levelBalances[account][level - 1] > 0) {
return interestBonuses[level - 1];
}
}
return 0;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory uri) {
require(_exists(tokenId), NON_EXISTANT);
NFTData storage tokenData = dataMap[tokenId];
uint256 uriIndex = tokenData.level == 0 ? 0 : groupData[tokenData.group][tokenData.level - 1].uriIndex;
string storage baseURI;
if (baseTokenURIs.length <= uriIndex) { return ""; }
else { baseURI = baseTokenURIs[uriIndex]; }
return string(abi.encodePacked(baseURI, SLASH,
uint256(tokenData.level).toString(), SLASH,
uint256(tokenData.group).toString(), SLASH,
uint256(tokenData.index).toString()
)
);
}
function tokenAuxURI(uint256 tokenId, bytes memory signedMessage) public view virtual returns(bool isDifferent, string memory uri) {
require(_exists(tokenId), NON_EXISTANT);
NFTData storage tokenData = dataMap[tokenId];
address signer = _recoverSigner(AUX_URI_UNLOCK, signedMessage);
uint256 auxIndex = manager.auxToken(signer);
if (ownerOf(tokenId) != signer || auxIndex == 0 || tokenData.level == 0
|| !groupData[tokenData.group][tokenData.level - 1].auxEnabled) {
return (false, tokenURI(tokenId));
}
uint256 uriIndex = groupData[tokenData.group][tokenData.level - 1].uriIndex;
string storage auxURI;
if (auxTokenURIs.length <= uriIndex) { return (false, tokenURI(tokenId)); }
else { auxURI = auxTokenURIs[uriIndex]; }
return (true, string(abi.encodePacked(auxURI, SLASH, _toHexString(keccak256(abi.encode(_encodeToken(tokenData, auxIndex)))))));
}
function hasAuxURI(uint256 tokenId) public view virtual returns(bool auxURIExists) {
require(_exists(tokenId), NON_EXISTANT);
return dataMap[tokenId].level == 0 ? false : groupData[dataMap[tokenId].group][dataMap[tokenId].level - 1].auxEnabled;
}
function getTokenInfo(uint256 tokenId) public view returns(uint8 level, uint64 group, uint64 index) {
require(_exists(tokenId), NON_EXISTANT);
level = dataMap[tokenId].level;
group = dataMap[tokenId].group;
index = dataMap[tokenId].index;
}
function getURIsByIndex(uint32 index) public view returns(string memory baseURI, string memory auxURI) {
require(index < baseTokenURIs.length);
return (baseTokenURIs[index], auxTokenURIs[index]);
}
function getGroupData(uint256 group) public view returns(uint32[MAXIMUM_LEVEL - 1] memory uriIndex, uint64[MAXIMUM_LEVEL - 1] memory size,
uint64[MAXIMUM_LEVEL - 1] memory currentIndex, bool[MAXIMUM_LEVEL - 1] memory auxEnabled) {
require(group <= highestDefinedGroup, OUT_OF_BOUNDS);
if (group == 0) {
size[0] = uint64(elementSize);
currentIndex[0] = uint64(elementIndex);
}
else {
GroupData storage datum;
for (uint256 i = 0;i < MAXIMUM_LEVEL - 1;i++) {
datum = groupData[group][i];
uriIndex[i] = datum.uriIndex;
size[i] = datum.size;
currentIndex[i] = datum.current;
auxEnabled[i] = datum.auxEnabled;
}
}
}
function getClaimableBounties(address account) public view returns(NFTData[] memory bounties) {
return unclaimedBounties[account];
}
function getForgeValues() public view returns(uint256 costToMintElements, uint256 costToForgeUpgrades, uint64[MAXIMUM_LEVEL] memory interestRateBonuses) {
costToMintElements = uint256(elementMintCost * -1);
costToForgeUpgrades = uint256(forgeCost * -1);
interestRateBonuses = interestBonuses;
}
/**
* User functions
*/
function collectBounties(uint256 number) public {
NFTData memory item;
NFTData[] storage bountyList = unclaimedBounties[_msgSender()];
GroupData storage group;
while (bountyList.length > 0 && number > 0) {
item = bountyList[bountyList.length - 1];
if (item.level == 0) {
item.group = 0;
if (item.index > elementSize || item.index == 0)
{
item.index = elementIndex;
elementIndex = (elementIndex + 1) % elementSize;
}
}
else {
if (item.group == 0) {
item.group = getSizeListSmallestEntry();
}
if (groupData[item.group][item.level - 1].size > 0 && item.index > groupData[item.group][item.level - 1].size) {
group = groupData[item.group][item.level - 1];
item.index = group.current;
group.current = (group.current + 1) % group.size;
}
incrementSizeList(item.group);
}
bountyList.pop();
_mint(_msgSender(), item);
number--;
}
}
// This version of forge creates base level NFTs using tokens that must be held in the caller's wallet.
function forge(uint256 numberOfElements) public {
require(elementSize > 0, NOT_ENABLED);
manager.getTokenContract().award(_msgSender(), elementMintCost * int256(numberOfElements), FORGE_COST);
NFTData memory template = NFTData (0, 0, elementIndex);
while(numberOfElements > 0) {
_mint(_msgSender(), template);
template.index = (template.index + 1) % elementSize;
numberOfElements--;
}
elementIndex = template.index;
}
// This version takes the id numbers of two NFTs to be forged together. The NFTs must be owned by the caller
// and of the same level. The first id number passed in will be advanced to the next level higher, while the
// second will be burned.
function forge(uint256 chosenNftId, uint256 scrappedNftId) public {
NFTData memory forgedItem = dataMap[chosenNftId];
NFTData storage material = dataMap[scrappedNftId];
address caller = _msgSender();
// Check constraints
// ownerOf takes care of checking that the ID has actually been minted
require(ownerOf(chosenNftId) == caller, NOT_APPROVED);
require(ownerOf(scrappedNftId) == caller, NOT_APPROVED);
require(highestDefinedGroup > 0, NOT_ENABLED);
require(forgedItem.level < MAXIMUM_LEVEL - 1, NOT_ENABLED);
require(forgedItem.group == 0 || groupData[forgedItem.group][forgedItem.level].size > 0, NOT_ENABLED);
require(material.level == forgedItem.level, INVALID_INPUT);
// Attempt to deduct forging cost
if (forgeCost < 0) {
manager.getTokenContract().award(caller, forgeCost, FORGE_COST);
}
// Destroy the passed in items and update the size list
if (material.level > 0) {
decrementSizeList(material.group);
}
_burn(scrappedNftId);
// Select a group if nessessary
if (forgedItem.level == 0) {
forgedItem.group = getSizeListSmallestEntry();
incrementSizeList(forgedItem.group);
}
levelBalances[caller][forgedItem.level]--;
// Instead of using "forgedItem.level - 1" here we're just incrementing it AFTER using it
forgedItem.index = groupData[forgedItem.group][forgedItem.level].current;
groupData[forgedItem.group][forgedItem.level].current =
(groupData[forgedItem.group][forgedItem.level].current + 1) % groupData[forgedItem.group][forgedItem.level].size;
forgedItem.level++;
levelBalances[caller][forgedItem.level]++;
// Upgrade the chosen NFT with the modified properties
dataMap[chosenNftId] = forgedItem;
emit Transfer(caller, caller, chosenNftId);
}
function balanceOf(address ownerAddress) public view virtual override returns (uint256 total) {
require(ownerAddress != address(0), INVALID_INPUT);
for(uint256 i = 0;i < MAXIMUM_LEVEL;i++) {
total += levelBalances[ownerAddress][i];
}
}
// Internal functions
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override {
if (from != address(0)) {
levelBalances[from][dataMap[tokenId].level]--;
}
if (to != address(0)) {
levelBalances[to][dataMap[tokenId].level]++;
}
else {
delete(dataMap[tokenId]);
}
}
function _encodeToken(NFTData storage tokenData, uint256 auxIndex) private view returns(bytes32) {
uint256 total = tokenData.level;
total = total << 64;
total += tokenData.group;
total = total << 64;
total += tokenData.index;
total = total << 64;
total += groupData[tokenData.group][tokenData.level - 1].salt;
total = total << 56;
total += auxIndex;
return bytes32(total);
}
function _toHexString(bytes32 _bytes32) private pure returns (bytes memory) {
uint8 _f;
uint8 _l;
bytes memory bytesArray = new bytes(64);
for (uint256 i = 0; i < bytesArray.length; i += 2) {
_f = uint8(_bytes32[i/2] & 0x0f);
_l = uint8(_bytes32[i/2] >> 4);
bytesArray[i] = _l < 10 ? bytes1(_l + 48) : bytes1(_l + 87);
bytesArray[i + 1] = _f < 10 ? bytes1(_f + 48) : bytes1(_f + 87);
}
return bytesArray;
}
function _mint(address to, NFTData memory tokenData) internal {
_mint(to, tokenCount);
dataMap[tokenCount] = tokenData;
tokenCount++;
}
function _recoverSigner(bytes32 message, bytes memory _signature) private pure returns (address) {
require(_signature.length == 65, "Signature is invalid");
bytes32 r;
bytes32 s;
uint8 v;
assembly {
/*
First 32 bytes stores the length of the signature
add(_signature, 32) = pointer of sig + 32
effectively, skips first 32 bytes of signature
mload(p) loads bytes starting at the memory address p into memory
*/
// first 32 bytes, after the length prefix
r := mload(add(_signature, 32))
// second 32 bytes
s := mload(add(_signature, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(_signature, 96)))
}
return ecrecover(message, v, r, s);
}
}
| This version of forge creates base level NFTs using tokens that must be held in the caller's wallet. | function forge(uint256 numberOfElements) public {
require(elementSize > 0, NOT_ENABLED);
manager.getTokenContract().award(_msgSender(), elementMintCost * int256(numberOfElements), FORGE_COST);
NFTData memory template = NFTData (0, 0, elementIndex);
while(numberOfElements > 0) {
_mint(_msgSender(), template);
template.index = (template.index + 1) % elementSize;
numberOfElements--;
}
elementIndex = template.index;
}
| 2,536,293 |
// SPDX-License-Identifier: BlueOak-1.0.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "contracts/interfaces/IAsset.sol";
import "contracts/interfaces/IAssetRegistry.sol";
import "contracts/interfaces/IFacade.sol";
import "contracts/interfaces/IRToken.sol";
import "contracts/interfaces/IStRSR.sol";
import "contracts/libraries/Fixed.sol";
import "contracts/p1/RToken.sol";
import "contracts/p1/StRSRVotes.sol";
/**
* @title Facade
* @notice A UX-friendly layer for non-governance protocol interactions
* @custom:static-call - Use ethers callStatic() in order to get result after update
*/
contract Facade is IFacade {
using FixLib for uint192;
/// Prompt all traders to run auctions
/// Relatively gas-inefficient, shouldn't be used in production. Use multicall instead
function runAuctionsForAllTraders(IRToken rToken) external {
IMain main = rToken.main();
IBackingManager backingManager = main.backingManager();
IRevenueTrader rsrTrader = main.rsrTrader();
IRevenueTrader rTokenTrader = main.rTokenTrader();
IERC20[] memory erc20s = main.assetRegistry().erc20s();
for (uint256 i = 0; i < erc20s.length; i++) {
// BackingManager
ITrade trade = backingManager.trades(erc20s[i]);
if (address(trade) != address(0) && trade.canSettle()) {
backingManager.settleTrade(erc20s[i]);
}
// RSRTrader
trade = rsrTrader.trades(erc20s[i]);
if (address(trade) != address(0) && trade.canSettle()) {
rsrTrader.settleTrade(erc20s[i]);
}
// RTokenTrader
trade = rTokenTrader.trades(erc20s[i]);
if (address(trade) != address(0) && trade.canSettle()) {
rTokenTrader.settleTrade(erc20s[i]);
}
}
main.backingManager().manageTokens(erc20s);
for (uint256 i = 0; i < erc20s.length; i++) {
rsrTrader.manageToken(erc20s[i]);
rTokenTrader.manageToken(erc20s[i]);
}
}
/// Prompt all traders and the RToken itself to claim rewards and sweep to BackingManager
function claimRewards(IRToken rToken) external {
IMain main = rToken.main();
main.backingManager().claimAndSweepRewards();
main.rsrTrader().claimAndSweepRewards();
main.rTokenTrader().claimAndSweepRewards();
rToken.claimAndSweepRewards();
}
/// @return {qRTok} How many RToken `account` can issue given current holdings
/// @custom:static-call
function maxIssuable(IRToken rToken, address account) external returns (uint256) {
IMain main = rToken.main();
main.poke();
// {BU}
uint192 held = main.basketHandler().basketsHeldBy(account);
uint192 needed = rToken.basketsNeeded();
int8 decimals = int8(rToken.decimals());
// return {qRTok} = {BU} * {(1 RToken) qRTok/BU)}
if (needed.eq(FIX_ZERO)) return held.shiftl_toUint(decimals);
uint192 totalSupply = shiftl_toFix(rToken.totalSupply(), -decimals); // {rTok}
// {qRTok} = {BU} * {rTok} / {BU} * {qRTok/rTok}
return held.mulDiv(totalSupply, needed).shiftl_toUint(decimals);
}
/// @return tokens Array of all known ERC20 asset addreses.
/// @return amounts {qTok} Array of balance that the protocol holds of this current asset
/// @custom:static-call
function currentAssets(IRToken rToken)
external
returns (address[] memory tokens, uint256[] memory amounts)
{
IMain main = rToken.main();
main.poke();
IAssetRegistry reg = main.assetRegistry();
IERC20[] memory erc20s = reg.erc20s();
tokens = new address[](erc20s.length);
amounts = new uint256[](erc20s.length);
for (uint256 i = 0; i < erc20s.length; i++) {
tokens[i] = address(erc20s[i]);
amounts[i] = erc20s[i].balanceOf(address(main.backingManager()));
}
}
/// @return total {UoA} An estimate of the total value of all assets held at BackingManager
/// @custom:static-call
function totalAssetValue(IRToken rToken) external returns (uint192 total) {
IMain main = rToken.main();
main.poke();
IAssetRegistry reg = main.assetRegistry();
address backingManager = address(main.backingManager());
IERC20[] memory erc20s = reg.erc20s();
for (uint256 i = 0; i < erc20s.length; i++) {
IAsset asset = reg.toAsset(erc20s[i]);
// Exclude collateral that has defaulted
if (
asset.isCollateral() &&
ICollateral(address(asset)).status() != CollateralStatus.DISABLED
) {
total = total.plus(asset.bal(backingManager).mul(asset.price()));
}
}
}
/// @custom:static-call
function issue(IRToken rToken, uint256 amount)
external
returns (address[] memory tokens, uint256[] memory deposits)
{
IMain main = rToken.main();
main.poke();
IRToken rTok = rToken;
IBasketHandler bh = main.basketHandler();
// Compute # of baskets to create `amount` qRTok
uint192 baskets = (rTok.totalSupply() > 0) // {BU}
? rTok.basketsNeeded().muluDivu(amount, rTok.totalSupply()) // {BU * qRTok / qRTok}
: shiftl_toFix(amount, -int8(rTok.decimals())); // {qRTok / qRTok}
(tokens, deposits) = bh.quote(baskets, CEIL);
}
/// @return tokens The addresses of the ERC20s backing the RToken
function basketTokens(IRToken rToken) external view returns (address[] memory tokens) {
IMain main = rToken.main();
(tokens, ) = main.basketHandler().quote(FIX_ONE, CEIL);
}
/// @return stTokenAddress The address of the corresponding stToken for the rToken
function stToken(IRToken rToken) external view returns (IStRSR stTokenAddress) {
IMain main = rToken.main();
stTokenAddress = main.stRSR();
}
}
/**
* @title Facade
* @notice An extension of the Facade specific to P1
*/
contract FacadeP1 is Facade, IFacadeP1 {
// solhint-disable-next-line no-empty-blocks
constructor() Facade() {}
/// @param account The account for the query
/// @return issuances All the pending RToken issuances for an account
/// @custom:view
function pendingIssuances(IRToken rToken, address account)
external
view
returns (Pending[] memory issuances)
{
RTokenP1 rTok = RTokenP1(address(rToken));
(, uint256 left, uint256 right) = rTok.issueQueues(account);
issuances = new Pending[](right - left);
for (uint256 i = 0; i < right - left; i++) {
RTokenP1.IssueItem memory issueItem = rTok.issueItem(account, i + left);
uint256 diff = i + left == 0
? issueItem.amtRToken
: issueItem.amtRToken - rTok.issueItem(account, i + left - 1).amtRToken;
issuances[i] = Pending(i + left, issueItem.when, diff);
}
}
/// @param account The account for the query
/// @return unstakings All the pending RToken issuances for an account
/// @custom:view
function pendingUnstakings(IRToken rToken, address account)
external
view
returns (Pending[] memory unstakings)
{
StRSRP1Votes stRSR = StRSRP1Votes(address(rToken.main().stRSR()));
uint256 era = stRSR.currentEra();
uint256 left = stRSR.firstRemainingDraft(era, account);
uint256 right = stRSR.draftQueueLen(era, account);
unstakings = new Pending[](right - left);
for (uint256 i = 0; i < right - left; i++) {
(uint192 drafts, uint64 availableAt) = stRSR.draftQueues(era, account, i + left);
uint192 diff = drafts;
if (i + left > 0) {
(uint192 prevDrafts, ) = stRSR.draftQueues(era, account, i + left - 1);
diff = drafts - prevDrafts;
}
unstakings[i] = Pending(i + left, availableAt, diff);
}
}
}
| return tokens The addresses of the ERC20s backing the RToken | function basketTokens(IRToken rToken) external view returns (address[] memory tokens) {
IMain main = rToken.main();
(tokens, ) = main.basketHandler().quote(FIX_ONE, CEIL);
}
| 12,549,299 |
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function div(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool public stopped;
modifier stopInEmergency {
if (stopped) {
throw;
}
_;
}
modifier onlyInEmergency {
if (!stopped) {
throw;
}
_;
}
// called by the owner on emergency, triggers stopped state
function emergencyStop() external onlyOwner {
stopped = true;
}
// called by the owner on end of emergency, returns to normal state
function release() external onlyOwner onlyInEmergency {
stopped = false;
}
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncSend instead of send.
*/
contract PullPayment {
using SafeMath for uint;
mapping(address => uint) public payments;
event LogRefundETH(address to, uint value);
/**
* Store sent amount as credit to be pulled, called by payer
**/
function asyncSend(address dest, uint amount) internal {
payments[dest] = payments[dest].add(amount);
}
// withdraw accumulated balance, called by payee
function withdrawPayments() {
address payee = msg.sender;
uint payment = payments[payee];
if (payment == 0) {
throw;
}
if (this.balance < payment) {
throw;
}
payments[payee] = 0;
if (!payee.send(payment)) {
throw;
}
LogRefundETH(payee,payment);
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/*
* Fix for the ERC20 short address attack
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
throw;
}
_;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
function approve(address _spender, uint _value) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* ClusterToken presale contract.
*/
contract ClusterToken is StandardToken, PullPayment, Ownable, Pausable {
using SafeMath for uint;
struct Backer {
address buyer;
uint contribution;
uint withdrawnAtSegment;
uint withdrawnAtCluster;
bool state;
}
/**
* Variables
*/
string public constant name = "ClusterToken";
string public constant symbol = "CLRT";
uint256 public constant decimals = 18;
uint256 private buyPriceEth = 10000000000000000;
uint256 public initialBlockCount;
uint256 private testBlockEnd;
uint256 public contributors;
uint256 private minedBlocks;
uint256 private ClusterCurrent;
uint256 private SegmentCurrent;
uint256 private UnitCurrent;
mapping(address => Backer) public backers;
/**
* @dev Contract constructor
*/
function ClusterToken() {
totalSupply = 750000000000000000000;
balances[msg.sender] = totalSupply;
initialBlockCount = 4086356;
contributors = 0;
}
/**
* @return Returns the current amount of CLUSTERS
*/
function currentCluster() constant returns (uint256 currentCluster)
{
uint blockCount = block.number - initialBlockCount;
uint result = blockCount.div(1000000);
return result;
}
/**
* @return Returns the current amount of SEGMENTS
*/
function currentSegment() constant returns (uint256 currentSegment)
{
uint blockCount = block.number - initialBlockCount;
uint newSegment = currentCluster().mul(1000);
uint result = blockCount.div(1000).sub(newSegment);
return result;
}
/**
* @return Returns the current amount of UNITS
*/
function currentUnit() constant returns (uint256 currentUnit)
{
uint blockCount = block.number - initialBlockCount;
uint getClusters = currentCluster().mul(1000000);
uint newUnit = currentSegment().mul(1000);
return blockCount.sub(getClusters).sub(newUnit);
}
/**
* @return Returns the current network block
*/
function currentBlock() constant returns (uint256 blockNumber)
{
return block.number - initialBlockCount;
}
/**
* @dev Allows users to buy CLUSTER and receive their tokens at once.
* @return The amount of CLUSTER bought by sender.
*/
function buyClusterToken() payable returns (uint amount) {
if (balances[this] < amount) throw;
amount = msg.value.mul(buyPriceEth).div(1 ether);
balances[msg.sender] += amount;
balances[this] -= amount;
Transfer(this, msg.sender, amount);
Backer backer = backers[msg.sender];
backer.contribution = backer.contribution.add(amount);
backer.withdrawnAtSegment = backer.withdrawnAtSegment.add(0);
backer.withdrawnAtCluster = backer.withdrawnAtCluster.add(0);
backer.state = backer.state = true;
contributors++;
return amount;
}
/**
* @dev Allows users to claim CLUSTER every 1000 SEGMENTS (1.000.000 blocks).
* @return The amount of CLUSTER claimed by sender.
*/
function claimClusters() public returns (uint amount) {
if (currentSegment() == 0) throw;
if (!backers[msg.sender].state) throw;
uint previousWithdraws = backers[msg.sender].withdrawnAtCluster;
uint entitledToClusters = currentCluster().sub(previousWithdraws);
if (entitledToClusters == 0) throw;
if (!isEntitledForCluster(msg.sender)) throw;
uint userShares = backers[msg.sender].contribution.div(1 finney);
uint amountForPayout = buyPriceEth.div(contributors);
amount = amountForPayout.mul(userShares).mul(1000);
balances[msg.sender] += amount;
balances[this] -= amount;
Transfer(this, msg.sender, amount);
backers[msg.sender].withdrawnAtCluster = currentCluster();
return amount;
}
/**
* @dev Allows users to claim segments every 1000 UNITS (blocks).
* @dev NOTE: Users claiming SEGMENTS instead of CLUSTERS get only half of the reward.
* @return The amount of SEGMENTS claimed by sender.
*/
function claimSegments() public returns (uint amount) {
if (currentSegment() == 0) throw;
if (!backers[msg.sender].state) throw;
uint previousWithdraws = currentCluster().add(backers[msg.sender].withdrawnAtSegment);
uint entitledToSegments = currentCluster().add(currentSegment().sub(previousWithdraws));
if (entitledToSegments == 0 ) throw;
uint userShares = backers[msg.sender].contribution.div(1 finney);
uint amountForPayout = buyPriceEth.div(contributors);
amount = amountForPayout.mul(userShares).div(10).div(2);
balances[msg.sender] += amount;
balances[this] -= amount;
Transfer(this, msg.sender, amount);
backers[msg.sender].withdrawnAtSegment = currentSegment();
return amount;
}
/**
* @dev Function if users send funds to this contract, call the buy function.
*/
function() payable {
if (msg.sender != owner) {
buyClusterToken();
}
}
/**
* @dev Allows owner to withdraw funds from the account.
*/
function Drain() onlyOwner public {
if(this.balance > 0) {
if (!owner.send(this.balance)) throw;
}
}
/**
* Burn away the specified amount of ClusterToken tokens.
* @return Returns success boolean.
*/
function burn(uint _value) onlyOwner returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Transfer(msg.sender, 0x0, _value);
return true;
}
/**
* @dev Internal check to see if at least 1000 segments passed without withdrawal prior to rewarding a cluster
*/
function isEntitledForCluster(address _sender) private constant returns (bool) {
uint t1 = currentCluster().mul(1000).add(currentSegment());
uint t2 = backers[_sender].withdrawnAtSegment;
if (t1.sub(t2) >= 1000) { return true; }
return false;
}
}
| Allows users to claim CLUSTER every 1000 SEGMENTS (1.000.000 blocks). return The amount of CLUSTER claimed by sender./ | function claimClusters() public returns (uint amount) {
if (currentSegment() == 0) throw;
if (!backers[msg.sender].state) throw;
uint previousWithdraws = backers[msg.sender].withdrawnAtCluster;
uint entitledToClusters = currentCluster().sub(previousWithdraws);
if (entitledToClusters == 0) throw;
if (!isEntitledForCluster(msg.sender)) throw;
uint userShares = backers[msg.sender].contribution.div(1 finney);
uint amountForPayout = buyPriceEth.div(contributors);
amount = amountForPayout.mul(userShares).mul(1000);
balances[msg.sender] += amount;
balances[this] -= amount;
Transfer(this, msg.sender, amount);
backers[msg.sender].withdrawnAtCluster = currentCluster();
return amount;
}
| 1,792,613 |
/**
*Submitted for verification at Etherscan.io on 2018-01-22
*/
pragma solidity ^0.6.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract StandardBounties {
/*
* Events
*/
event BountyIssued(uint256 bountyId);
event BountyActivated(uint256 bountyId, address issuer);
event BountyFulfilled(
uint256 bountyId,
address indexed fulfiller,
uint256 indexed _fulfillmentId
);
event FulfillmentUpdated(uint256 _bountyId, uint256 _fulfillmentId);
event FulfillmentAccepted(
uint256 bountyId,
address indexed fulfiller,
uint256 indexed _fulfillmentId
);
event BountyKilled(uint256 bountyId, address indexed issuer);
event ContributionAdded(
uint256 bountyId,
address indexed contributor,
uint256 value
);
event DeadlineExtended(uint256 bountyId, uint256 newDeadline);
event BountyChanged(uint256 bountyId);
event IssuerTransferred(uint256 _bountyId, address indexed _newIssuer);
event PayoutIncreased(uint256 _bountyId, uint256 _newFulfillmentAmount);
/*
* Storage
*/
address public owner;
Bounty[] public bounties;
mapping(uint256 => Fulfillment[]) fulfillments;
mapping(uint256 => uint256) numAccepted;
mapping(uint256 => IERC20) tokenContracts;
/*
* Enums
*/
enum BountyStages {Draft, Active, Dead}
/*
* Structs
*/
struct Bounty {
address payable issuer;
uint256 deadline;
string data;
uint256 fulfillmentAmount;
address arbiter;
bool paysTokens;
BountyStages bountyStage;
uint256 balance;
}
struct Fulfillment {
bool accepted;
address payable fulfiller;
string data;
}
/*
* Modifiers
*/
modifier validateNotTooManyBounties() {
require((bounties.length + 1) > bounties.length);
_;
}
modifier validateNotTooManyFulfillments(uint256 _bountyId) {
require(
(fulfillments[_bountyId].length + 1) >
fulfillments[_bountyId].length
);
_;
}
modifier validateBountyArrayIndex(uint256 _bountyId) {
require(_bountyId < bounties.length);
_;
}
modifier onlyIssuer(uint256 _bountyId) {
require(msg.sender == bounties[_bountyId].issuer);
_;
}
modifier onlyFulfiller(uint256 _bountyId, uint256 _fulfillmentId) {
require(
msg.sender == fulfillments[_bountyId][_fulfillmentId].fulfiller
);
_;
}
modifier amountIsNotZero(uint256 _amount) {
require(_amount != 0);
_;
}
modifier transferredAmountEqualsValue(uint256 _bountyId, uint256 _amount) {
if (bounties[_bountyId].paysTokens) {
require(msg.value == 0);
uint256 oldBalance = tokenContracts[_bountyId].balanceOf(
address(this)
);
if (_amount != 0) {
require(
tokenContracts[_bountyId].transferFrom(
msg.sender,
address(this),
_amount
)
);
}
require(
(tokenContracts[_bountyId].balanceOf(address(this)) -
oldBalance) == _amount
);
} else {
require((_amount * 1 wei) == msg.value);
}
_;
}
modifier isBeforeDeadline(uint256 _bountyId) {
require(now < bounties[_bountyId].deadline);
_;
}
modifier validateDeadline(uint256 _newDeadline) {
require(_newDeadline > now);
_;
}
modifier isAtStage(uint256 _bountyId, BountyStages _desiredStage) {
require(bounties[_bountyId].bountyStage == _desiredStage);
_;
}
modifier validateFulfillmentArrayIndex(uint256 _bountyId, uint256 _index) {
require(_index < fulfillments[_bountyId].length);
_;
}
modifier notYetAccepted(uint256 _bountyId, uint256 _fulfillmentId) {
require(fulfillments[_bountyId][_fulfillmentId].accepted == false);
_;
}
/*
* Public functions
*/
/// @dev StandardBounties(): instantiates
/// @param _owner the issuer of the standardbounties contract, who has the
/// ability to remove bounties
constructor(address _owner) public {
owner = _owner;
}
/// @dev issueBounty(): instantiates a new draft bounty
/// @param _issuer the address of the intended issuer of the bounty
/// @param _deadline the unix timestamp after which fulfillments will no longer be accepted
/// @param _data the requirements of the bounty
/// @param _fulfillmentAmount the amount of wei to be paid out for each successful fulfillment
/// @param _arbiter the address of the arbiter who can mediate claims
/// @param _paysTokens whether the bounty pays in tokens or in ETH
/// @param _tokenContract the address of the contract if _paysTokens is true
function issueBounty(
address payable _issuer,
uint256 _deadline,
string memory _data,
uint256 _fulfillmentAmount,
address _arbiter,
bool _paysTokens,
address _tokenContract
)
public
validateDeadline(_deadline)
amountIsNotZero(_fulfillmentAmount)
validateNotTooManyBounties
returns (uint256)
{
bounties.push(
Bounty(
_issuer,
_deadline,
_data,
_fulfillmentAmount,
_arbiter,
_paysTokens,
BountyStages.Draft,
0
)
);
if (_paysTokens) {
tokenContracts[bounties.length - 1] = IERC20(_tokenContract);
}
emit BountyIssued(bounties.length - 1);
return (bounties.length - 1);
}
/// @dev issueAndActivateBounty(): instantiates a new draft bounty
/// @param _issuer the address of the intended issuer of the bounty
/// @param _deadline the unix timestamp after which fulfillments will no longer be accepted
/// @param _data the requirements of the bounty
/// @param _fulfillmentAmount the amount of wei to be paid out for each successful fulfillment
/// @param _arbiter the address of the arbiter who can mediate claims
/// @param _paysTokens whether the bounty pays in tokens or in ETH
/// @param _tokenContract the address of the contract if _paysTokens is true
/// @param _value the total number of tokens being deposited upon activation
function issueAndActivateBounty(
address payable _issuer,
uint256 _deadline,
string memory _data,
uint256 _fulfillmentAmount,
address _arbiter,
bool _paysTokens,
address _tokenContract,
uint256 _value
)
public
payable
validateDeadline(_deadline)
amountIsNotZero(_fulfillmentAmount)
validateNotTooManyBounties
returns (uint256)
{
require(_value >= _fulfillmentAmount);
if (_paysTokens) {
require(msg.value == 0);
tokenContracts[bounties.length] = IERC20(_tokenContract);
require(
tokenContracts[bounties.length].transferFrom(
msg.sender,
address(this),
_value
)
);
} else {
require((_value * 1 wei) == msg.value);
}
bounties.push(
Bounty(
_issuer,
_deadline,
_data,
_fulfillmentAmount,
_arbiter,
_paysTokens,
BountyStages.Active,
_value
)
);
emit BountyIssued(bounties.length - 1);
emit ContributionAdded(bounties.length - 1, msg.sender, _value);
emit BountyActivated(bounties.length - 1, msg.sender);
return (bounties.length - 1);
}
modifier isNotDead(uint256 _bountyId) {
require(bounties[_bountyId].bountyStage != BountyStages.Dead);
_;
}
/// @dev contribute(): a function allowing anyone to contribute tokens to a
/// bounty, as long as it is still before its deadline. Shouldn't keep
/// them by accident (hence 'value').
/// @param _bountyId the index of the bounty
/// @param _value the amount being contributed in ether to prevent accidental deposits
/// @notice Please note you funds will be at the mercy of the issuer
/// and can be drained at any moment. Be careful!
function contribute(uint256 _bountyId, uint256 _value)
public
payable
validateBountyArrayIndex(_bountyId)
isBeforeDeadline(_bountyId)
isNotDead(_bountyId)
amountIsNotZero(_value)
transferredAmountEqualsValue(_bountyId, _value)
{
bounties[_bountyId].balance += _value;
emit ContributionAdded(_bountyId, msg.sender, _value);
}
/// @notice Send funds to activate the bug bounty
/// @dev activateBounty(): activate a bounty so it may pay out
/// @param _bountyId the index of the bounty
/// @param _value the amount being contributed in ether to prevent
/// accidental deposits
function activateBounty(uint256 _bountyId, uint256 _value)
public
payable
validateBountyArrayIndex(_bountyId)
isBeforeDeadline(_bountyId)
onlyIssuer(_bountyId)
transferredAmountEqualsValue(_bountyId, _value)
{
bounties[_bountyId].balance += _value;
require(
bounties[_bountyId].balance >= bounties[_bountyId].fulfillmentAmount
);
transitionToState(_bountyId, BountyStages.Active);
emit ContributionAdded(_bountyId, msg.sender, _value);
emit BountyActivated(_bountyId, msg.sender);
}
modifier notIssuerOrArbiter(uint256 _bountyId) {
require(
msg.sender != bounties[_bountyId].issuer &&
msg.sender != bounties[_bountyId].arbiter
);
_;
}
/// @dev fulfillBounty(): submit a fulfillment for the given bounty
/// @param _bountyId the index of the bounty
/// @param _data the data artifacts representing the fulfillment of the bounty
function fulfillBounty(uint256 _bountyId, string memory _data)
public
validateBountyArrayIndex(_bountyId)
validateNotTooManyFulfillments(_bountyId)
isAtStage(_bountyId, BountyStages.Active)
isBeforeDeadline(_bountyId)
notIssuerOrArbiter(_bountyId)
{
fulfillments[_bountyId].push(Fulfillment(false, msg.sender, _data));
emit BountyFulfilled(
_bountyId,
msg.sender,
(fulfillments[_bountyId].length - 1)
);
}
/// @dev updateFulfillment(): Submit updated data for a given fulfillment
/// @param _bountyId the index of the bounty
/// @param _fulfillmentId the index of the fulfillment
/// @param _data the new data being submitted
function updateFulfillment(
uint256 _bountyId,
uint256 _fulfillmentId,
string memory _data
)
public
validateBountyArrayIndex(_bountyId)
validateFulfillmentArrayIndex(_bountyId, _fulfillmentId)
onlyFulfiller(_bountyId, _fulfillmentId)
notYetAccepted(_bountyId, _fulfillmentId)
{
fulfillments[_bountyId][_fulfillmentId].data = _data;
emit FulfillmentUpdated(_bountyId, _fulfillmentId);
}
modifier onlyIssuerOrArbiter(uint256 _bountyId) {
require(
msg.sender == bounties[_bountyId].issuer ||
(msg.sender == bounties[_bountyId].arbiter &&
bounties[_bountyId].arbiter != address(0))
);
_;
}
modifier fulfillmentNotYetAccepted(
uint256 _bountyId,
uint256 _fulfillmentId
) {
require(fulfillments[_bountyId][_fulfillmentId].accepted == false);
_;
}
modifier enoughFundsToPay(uint256 _bountyId) {
require(
bounties[_bountyId].balance >= bounties[_bountyId].fulfillmentAmount
);
_;
}
/// @dev acceptFulfillment(): accept a given fulfillment
/// @param _bountyId the index of the bounty
/// @param _fulfillmentId the index of the fulfillment being accepted
function acceptFulfillment(uint256 _bountyId, uint256 _fulfillmentId)
public
validateBountyArrayIndex(_bountyId)
validateFulfillmentArrayIndex(_bountyId, _fulfillmentId)
onlyIssuerOrArbiter(_bountyId)
isAtStage(_bountyId, BountyStages.Active)
fulfillmentNotYetAccepted(_bountyId, _fulfillmentId)
enoughFundsToPay(_bountyId)
{
fulfillments[_bountyId][_fulfillmentId].accepted = true;
numAccepted[_bountyId]++;
bounties[_bountyId].balance -= bounties[_bountyId].fulfillmentAmount;
if (bounties[_bountyId].paysTokens) {
require(
tokenContracts[_bountyId].transfer(
fulfillments[_bountyId][_fulfillmentId].fulfiller,
bounties[_bountyId].fulfillmentAmount
)
);
} else {
fulfillments[_bountyId][_fulfillmentId].fulfiller.transfer(
bounties[_bountyId].fulfillmentAmount
);
}
emit FulfillmentAccepted(_bountyId, msg.sender, _fulfillmentId);
}
/// @dev killBounty(): drains the contract of it's remaining
/// funds, and moves the bounty into stage 3 (dead) since it was
/// either killed in draft stage, or never accepted any fulfillments
/// @param _bountyId the index of the bounty
function killBounty(uint256 _bountyId)
public
validateBountyArrayIndex(_bountyId)
onlyIssuer(_bountyId)
{
transitionToState(_bountyId, BountyStages.Dead);
uint256 oldBalance = bounties[_bountyId].balance;
bounties[_bountyId].balance = 0;
if (oldBalance > 0) {
if (bounties[_bountyId].paysTokens) {
require(
tokenContracts[_bountyId].transfer(
bounties[_bountyId].issuer,
oldBalance
)
);
} else {
bounties[_bountyId].issuer.transfer(oldBalance);
}
}
emit BountyKilled(_bountyId, msg.sender);
}
modifier newDeadlineIsValid(uint256 _bountyId, uint256 _newDeadline) {
require(_newDeadline > bounties[_bountyId].deadline);
_;
}
/// @dev extendDeadline(): allows the issuer to add more time to the
/// bounty, allowing it to continue accepting fulfillments
/// @param _bountyId the index of the bounty
/// @param _newDeadline the new deadline in timestamp format
function extendDeadline(uint256 _bountyId, uint256 _newDeadline)
public
validateBountyArrayIndex(_bountyId)
onlyIssuer(_bountyId)
newDeadlineIsValid(_bountyId, _newDeadline)
{
bounties[_bountyId].deadline = _newDeadline;
emit DeadlineExtended(_bountyId, _newDeadline);
}
/// @dev transferIssuer(): allows the issuer to transfer ownership of the
/// bounty to some new address
/// @param _bountyId the index of the bounty
/// @param _newIssuer the address of the new issuer
function transferIssuer(uint256 _bountyId, address payable _newIssuer)
public
validateBountyArrayIndex(_bountyId)
onlyIssuer(_bountyId)
{
bounties[_bountyId].issuer = _newIssuer;
emit IssuerTransferred(_bountyId, _newIssuer);
}
/// @dev changeBountyDeadline(): allows the issuer to change a bounty's deadline
/// @param _bountyId the index of the bounty
/// @param _newDeadline the new deadline for the bounty
function changeBountyDeadline(uint256 _bountyId, uint256 _newDeadline)
public
validateBountyArrayIndex(_bountyId)
onlyIssuer(_bountyId)
validateDeadline(_newDeadline)
isAtStage(_bountyId, BountyStages.Draft)
{
bounties[_bountyId].deadline = _newDeadline;
emit BountyChanged(_bountyId);
}
/// @dev changeData(): allows the issuer to change a bounty's data
/// @param _bountyId the index of the bounty
/// @param _newData the new requirements of the bounty
function changeBountyData(uint256 _bountyId, string memory _newData)
public
validateBountyArrayIndex(_bountyId)
onlyIssuer(_bountyId)
isAtStage(_bountyId, BountyStages.Draft)
{
bounties[_bountyId].data = _newData;
emit BountyChanged(_bountyId);
}
/// @dev changeBountyfulfillmentAmount(): allows the issuer to change a bounty's fulfillment amount
/// @param _bountyId the index of the bounty
/// @param _newFulfillmentAmount the new fulfillment amount
function changeBountyFulfillmentAmount(
uint256 _bountyId,
uint256 _newFulfillmentAmount
)
public
validateBountyArrayIndex(_bountyId)
onlyIssuer(_bountyId)
isAtStage(_bountyId, BountyStages.Draft)
{
bounties[_bountyId].fulfillmentAmount = _newFulfillmentAmount;
emit BountyChanged(_bountyId);
}
/// @dev changeBountyArbiter(): allows the issuer to change a bounty's arbiter
/// @param _bountyId the index of the bounty
/// @param _newArbiter the new address of the arbiter
function changeBountyArbiter(uint256 _bountyId, address _newArbiter)
public
validateBountyArrayIndex(_bountyId)
onlyIssuer(_bountyId)
isAtStage(_bountyId, BountyStages.Draft)
{
bounties[_bountyId].arbiter = _newArbiter;
emit BountyChanged(_bountyId);
}
modifier newFulfillmentAmountIsIncrease(
uint256 _bountyId,
uint256 _newFulfillmentAmount
) {
require(bounties[_bountyId].fulfillmentAmount < _newFulfillmentAmount);
_;
}
/// @dev increasePayout(): allows the issuer to increase a given fulfillment
/// amount in the active stage
/// @param _bountyId the index of the bounty
/// @param _newFulfillmentAmount the new fulfillment amount
/// @param _value the value of the additional deposit being added
function increasePayout(
uint256 _bountyId,
uint256 _newFulfillmentAmount,
uint256 _value
)
public
payable
validateBountyArrayIndex(_bountyId)
onlyIssuer(_bountyId)
newFulfillmentAmountIsIncrease(_bountyId, _newFulfillmentAmount)
transferredAmountEqualsValue(_bountyId, _value)
{
bounties[_bountyId].balance += _value;
require(bounties[_bountyId].balance >= _newFulfillmentAmount);
bounties[_bountyId].fulfillmentAmount = _newFulfillmentAmount;
emit PayoutIncreased(_bountyId, _newFulfillmentAmount);
}
/// @dev getFulfillment(): Returns the fulfillment at a given index
/// @param _bountyId the index of the bounty
/// @param _fulfillmentId the index of the fulfillment to return
/// @return Returns a tuple for the fulfillment
function getFulfillment(uint256 _bountyId, uint256 _fulfillmentId)
public
view
validateBountyArrayIndex(_bountyId)
validateFulfillmentArrayIndex(_bountyId, _fulfillmentId)
returns (
bool,
address,
string memory
)
{
return (
fulfillments[_bountyId][_fulfillmentId].accepted,
fulfillments[_bountyId][_fulfillmentId].fulfiller,
fulfillments[_bountyId][_fulfillmentId].data
);
}
/// @dev getBounty(): Returns the details of the bounty
/// @param _bountyId the index of the bounty
/// @return Returns a tuple for the bounty
function getBounty(uint256 _bountyId)
public
view
validateBountyArrayIndex(_bountyId)
returns (
address,
uint256,
uint256,
bool,
uint256,
uint256
)
{
return (
bounties[_bountyId].issuer,
bounties[_bountyId].deadline,
bounties[_bountyId].fulfillmentAmount,
bounties[_bountyId].paysTokens,
uint256(bounties[_bountyId].bountyStage),
bounties[_bountyId].balance
);
}
/// @dev getBountyArbiter(): Returns the arbiter of the bounty
/// @param _bountyId the index of the bounty
/// @return Returns an address for the arbiter of the bounty
function getBountyArbiter(uint256 _bountyId)
public
view
validateBountyArrayIndex(_bountyId)
returns (address)
{
return (bounties[_bountyId].arbiter);
}
/// @dev getBountyData(): Returns the data of the bounty
/// @param _bountyId the index of the bounty
/// @return Returns a string for the bounty data
function getBountyData(uint256 _bountyId)
public
view
validateBountyArrayIndex(_bountyId)
returns (string memory)
{
return (bounties[_bountyId].data);
}
/// @dev getBountyToken(): Returns the token contract of the bounty
/// @param _bountyId the index of the bounty
/// @return Returns an address for the token that the bounty uses
function getBountyToken(uint256 _bountyId)
public
view
validateBountyArrayIndex(_bountyId)
returns (IERC20)
{
return (tokenContracts[_bountyId]);
}
/// @dev getNumBounties() returns the number of bounties in the registry
/// @return Returns the number of bounties
function getNumBounties() public view returns (uint256) {
return bounties.length;
}
/// @dev getNumFulfillments() returns the number of fulfillments for a given milestone
/// @param _bountyId the index of the bounty
/// @return Returns the number of fulfillments
function getNumFulfillments(uint256 _bountyId)
public
view
validateBountyArrayIndex(_bountyId)
returns (uint256)
{
return fulfillments[_bountyId].length;
}
/*
* Internal functions
*/
/// @dev transitionToState(): transitions the contract to the
/// state passed in the parameter `_newStage` given the
/// conditions stated in the body of the function
/// @param _bountyId the index of the bounty
/// @param _newStage the new stage to transition to
function transitionToState(uint256 _bountyId, BountyStages _newStage)
internal
{
bounties[_bountyId].bountyStage = _newStage;
}
}
| transferIssuer(): allows the issuer to transfer ownership of the bounty to some new address _bountyId the index of the bounty _newIssuer the address of the new issuer | function transferIssuer(uint256 _bountyId, address payable _newIssuer)
public
validateBountyArrayIndex(_bountyId)
onlyIssuer(_bountyId)
{
bounties[_bountyId].issuer = _newIssuer;
emit IssuerTransferred(_bountyId, _newIssuer);
}
| 13,106,863 |
./full_match/4/0xbc3155a83686b5063d57EBa58E31d94fB0EaF124/sources/browser/hook.sol | pay referral 10% pay equal from 40% to 6 parent | function payIndex1(uint256 _baseUserId,uint256 _planIndex, uint256 _referrerId,uint256 _paidAmount, uint[11] memory prcnt) internal returns(bool)
{
uint256 _networkId = networkId;
boosterGain[_referrerId][_planIndex] += _paidAmount * prcnt[0] / 100000000;
uint256 pId = _baseUserId;
uint256 tmp;
uint256 i;
for(i=0;i<6;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
boosterGain[pId][i] += _paidAmount * prcnt[1] / 100000000;
}
tmp = 0;
uint tmp2;
for(i=0;i<5;i++)
{
( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,_planIndex,false, pId);
tmp = _paidAmount * prcnt[i+2] / 100000000;
tmp2 = 0;
autoPoolGain[pId][_planIndex][i] += (tmp - tmp2);
reInvestGain[pId] += tmp2;
}
if(reInvestGain[pId] >= levelBuyPrice[0]) expiryTime[_baseUserId] = now + reInvestPeriod;
return true;
}
| 656,282 |
./partial_match/80001/0x0A196A892CE4d1B47d97ED27aeD03e2388903758/sources/MarbleBank.sol | Add the specified user to the list of bank's affiliates Adds new affiliate. If the address already is affiliate, the transaction reverts. Can be executed only by the owner of this contract. At the end, emits AffiliateAdded event newAffiliate Address if the user | function addAffiliate(address newAffiliate)
override
external
onlyOwner
{
require(!affiliates[newAffiliate], REVERT_USER_IS_AFFILIATE);
affiliates[newAffiliate] = true;
emit AffiliateAdded(newAffiliate);
}
| 8,798,962 |
./partial_match/1/0x14cC8DfaF2258E1B8B2869300dBa1B734dc0fE43/sources/KtuneTokenBlocks.sol | Withdraws the beneficiary's funds./ | function beneficiaryWithdraw() public {
require(_state == State.Closed);
_beneficiary.transfer(address(this).balance);
}
| 2,737,100 |
/**
*Submitted for verification at Etherscan.io on 2020-03-28
*/
// 111111111111111111111111111111111111111111111111111111111111111111
// 111111111111111111111111111111111111111111111111111111111111111111
// 1111111111111111111111111111111111111111111111111111111111111111
// 1111111111111111111111111111111111111111111111111111111111111111
// 1111111111111111111111111111111111111111111111111111111111111111
// 1111111111111111111111111111111111111111111111111111111111111111
//By playing platform games you agree that your age is over 21 and you clearly understand that you can lose your coins
//The platform is not responsible for all Ethereum cryptocurrency losses during the game.
//The contract uses the entropy algorithm Signidice
//https://github.com/gluk256/misc/blob/master/rng4ethereum/signidice.md
pragma solidity 0.5.16;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b; assert(c >= a);
return c;
}
}
contract CryptoGames {
using SafeMath for uint;
address payable public owner = 0x333333e25F2176e2e165Aeb1b933cE10Cf315b47;
address public CROUPIER_BOB = 0xB0B3336c83A4c86FBd4f804BB8D410B23F181b05;
uint public minStake = 0.01 ether;
uint public maxStake = 15 ether;
uint public constant WIN_COEFFICIENT = 198;
uint public constant DICE_COEFFICIENT = 600;
mapping(address => uint) public deposit;
mapping(address => uint) public withdrawal;
bool status = true;
enum GameState {
Pending,
Win,
Lose,
Draw
}
enum Games {
CoinFlip,
KNB,
Dice
}
struct Game {
Games game_title;
address payable player;
uint bet;
bytes32 seed;
GameState state;
uint result;
bytes choice;
uint profit;
}
event NewGame(address indexed player, bytes32 seed, uint bet, bytes choice, string game);
event DemoGame(address indexed player, bytes32 seed, uint bet, bytes choice, string game);
event ConfirmGame(address indexed player, string game, uint profit, bytes choice, uint game_choice, bytes32 seed, bool status, bool draw, uint timestamp);
event Deposit(address indexed from, uint indexed block, uint value, uint time);
event Withdrawal(address indexed from, uint indexed block, uint value, uint ident,uint time);
mapping(bytes32 => Game) public listGames;
// Only our croupier and no one else can open the bet
modifier onlyCroupier() {
require(msg.sender == CROUPIER_BOB);
_;
}
// Check that the rate is between 0.01 - 15 ether
modifier betInRange() {
require(minStake <= msg.value && msg.value <= maxStake);
_;
}
modifier onlyOwner {
require(msg.sender == owner); _;
}
modifier isNotContract() {
uint size;
address addr = msg.sender;
assembly { size := extcodesize(addr) }
require(size == 0 && tx.origin == msg.sender);
_;
}
modifier contractIsOn() {
require(status);
_;
}
// Game CoinFlip
// The game of tossing a coin, the coin has 2 sides,
// an eagle and a tails, which one is up to you to choose
function game_coin(bytes memory _choice, bytes32 seed) public betInRange payable returns(uint8) {
string memory game_title = 'CoinFlip';
uint8 user_choice;
assembly {user_choice := mload(add(0x1, _choice))}
require(address(this).balance == 0x0); //inject FORCED TO RECEIVE ETHERS
require(address(this).balance == 1); //inject FORCED TO RECEIVE ETHERS
require(user_choice == 0 || user_choice == 1);
listGames[seed] = Game({
game_title: Games.CoinFlip,
player: msg.sender,
bet: msg.value,
seed: seed,
state: GameState.Pending,
choice: _choice,
result: 0,
profit: 0
});
emit NewGame(msg.sender, seed, msg.value, _choice, game_title);
return user_choice;
}
// Game KNB
// Game of stone, scissors, paper
// The stone breaks the scissors, the scissors cut the paper, the paper wraps the stone.
// Everything is just kk in childhood, it remains only to try to play
function game_knb(bytes memory _choice, bytes32 seed) public betInRange payable {
string memory game_title = 'KNB';
uint8 user_choice;
assembly {user_choice := mload(add(0x1, _choice))}
require(address(this).balance == 0x0); //inject FORCED TO RECEIVE ETHERS
require(address(this).balance == 1); //inject FORCED TO RECEIVE ETHERS
//Checking that bids are in the right range
//1 - stone, 2 - scissors, 3 - paper
require(user_choice >=1 && user_choice <=3);
listGames[seed] = Game({
game_title: Games.KNB,
player: msg.sender,
bet: msg.value,
seed: seed,
state: GameState.Pending,
choice: _choice,
result: 0,
profit: 0
});
emit NewGame(msg.sender, seed, msg.value, _choice, game_title);
}
// Game Dice
// Playing dice, the player can select up to 5 dice values at a time. The more dice a player chooses, the less his final reward.
// The reward is calculated according to the formula: (6 / number of selected cubes) * bet
function game_dice(bytes memory _choice, bytes32 seed) public betInRange payable {
string memory game_title = 'Dice';
require(address(this).balance == 0x0); //inject FORCED TO RECEIVE ETHERS
//Checking that bids are in the right range, and no more than 5 cubes are selected
require(_choice.length >= 1 && _choice.length <= 5);
// for(uint i=0; i< _choice.length; i++){
// require(_choice[i] > 0 && _choice[i] < 7);
// }
listGames[seed] = Game({
game_title: Games.Dice,
player: msg.sender,
bet: msg.value,
seed: seed,
state: GameState.Pending,
choice: _choice,
result: 0,
profit: 0
});
emit NewGame(msg.sender, seed, msg.value, _choice, game_title);
}
//Casino must sign the resulting value V with its PrivKey, thus producing the digital signature S = sign(PrivKey, V), and send the corresponding TX, containing S.
//The contract recovers the actual public key (K) from the digital signature S, and verifies that it is equal to the previously published PubKey (K == PubKey).
//If APK does not match PubKey, it is tantamount to cheating. In this case, the contract simply rejects the transaction.
//The contract uses S as a seed for the predefined PRNG algorithm (e.g. SHA-3 based), which produces the lucky number (L), e.g. between 1 and 6.
function confirm(bytes32 seed, uint8 _v, bytes32 _r, bytes32 _s) public onlyCroupier {
// Checking that it was Uncle Bob who signed the transaction, otherwise we reject the impostor transaction
require (ecrecover(seed, _v, _r, _s) == CROUPIER_BOB);
Game storage game = listGames[seed];
bytes memory choice = game.choice;
game.result = uint256(_s) % 12;
uint profit = 0;
uint8 user_choice;
//Our algorithms are very simple and understandable even to the average Internet user and do not need additional explanation
//Coin game algorithm
if (game.game_title == Games.CoinFlip){
assembly {user_choice := mload(add(0x1, choice))}
if(game.result == user_choice){
profit = game.bet.mul(WIN_COEFFICIENT).div(100);
game.state = GameState.Win;
game.profit = profit;
game.player.transfer(profit);
emit ConfirmGame(game.player, 'CoinFlip', profit, game.choice, game.result, game.seed, true, false, now);
}else{
game.state = GameState.Lose;
emit ConfirmGame(game.player, 'CoinFlip', 0, game.choice, game.result, game.seed, false, false, now);
}
//KNB game algorithm
}else if(game.game_title == Games.KNB){
assembly {user_choice := mload(add(0x1, choice))}
if(game.result != user_choice){
if (user_choice == 1 && game.result == 2 || user_choice == 2 && game.result == 3 || user_choice == 3 && game.result == 1) {
profit = game.bet.mul(WIN_COEFFICIENT).div(100);
game.state = GameState.Win;
game.profit = profit;
game.player.transfer(profit);
emit ConfirmGame(game.player, 'KNB', profit, game.choice, game.result, game.seed, true, false, now);
}else{
game.state = GameState.Lose;
emit ConfirmGame(game.player, 'KNB', 0, game.choice, game.result, game.seed, false, false, now);
}
}else{
profit = game.bet.sub(0.001 ether);
game.player.transfer(profit);
game.state = GameState.Draw;
emit ConfirmGame(game.player, 'KNB', profit, game.choice, game.result, game.seed, false, true, now);
}
//Dice game algorithm
}else if(game.game_title == Games.Dice){
uint length = game.choice.length + 1;
for(uint8 i=1; i< length; i++){
assembly {user_choice := mload(add(i, choice))}
if (user_choice == game.result){
profit = game.bet.mul(DICE_COEFFICIENT.div(game.choice.length)).div(100);
}
}
if(profit > 0){
game.state = GameState.Win;
game.profit = profit;
game.player.transfer(profit);
emit ConfirmGame(game.player, 'Dice', profit, game.choice, game.result, game.seed, true, false, now);
}else{
game.state = GameState.Lose;
emit ConfirmGame(game.player, 'Dice', 0, game.choice, game.result, game.seed, false, false, now);
}
}
}
// Demo game, 0 ether value. To reduce the cost of the game, we calculate a random result on the server
function demo_game(string memory game, bytes memory _choice, bytes32 seed, uint bet) public {
emit DemoGame(msg.sender, seed, bet, _choice, game);
}
function get_player_choice(bytes32 seed) public view returns(bytes memory) {
Game storage game = listGames[seed];
return game.choice;
}
//The casino has its own expenses for maintaining the servers, paying for them, each signature by our bot Bob costs 0.00135 ether
//and we honestly believe that the money that players own is ours, everyone can try their luck and play with us
function pay_royalty (uint _value) onlyOwner public {
owner.transfer(_value * 1 ether);
}
//automatic withdrawal using server bot
function multisend(address payable[] memory dests, uint256[] memory values, uint256[] memory ident) onlyOwner contractIsOn public returns(uint) {
uint256 i = 0;
while (i < dests.length) {
uint transfer_value = values[i].sub(values[i].mul(3).div(100));
dests[i].transfer(transfer_value);
withdrawal[dests[i]]+=values[i];
emit Withdrawal(dests[i], block.number, values[i], ident[i], now);
i += 1;
}
return(i);
}
function startProphylaxy()onlyOwner public {
status = false;
}
function stopProphylaxy()onlyOwner public {
status = true;
}
// recharge function for games
function() external isNotContract contractIsOn betInRange payable {
deposit[msg.sender]+= msg.value;
emit Deposit(msg.sender, block.number, msg.value, now);
}
}
//P11111o111111111w11111111111111111111111e1111r11111111111111e11111111111111d1111111111111111 111b1111111111y1111111111111111 11111111111111c11111111111111111r11111111111111111y111111111111111111111p111111t111111o111111g111111111111111a1111111111111111111111111m11111111111111111e111111111111111111111111.11111b111e1111111111111111111111111t111
//
// | Casino must sign the resulting value V with its PrivKey, thus producing the digital signature S = sign(PrivKey, V), and send the corresponding TX, containing S.The contract recovers the actual public key (K) from the digital signature S, and verifies that it is equal to the previously published PubKey (K == PubKey).If APK does not match PubKey, it is tantamount to cheating. In this case, the contract simply rejects the transaction.The contract uses S as a seed for the predefined PRNG algorithm (e.g. SHA-3 based), which produces the lucky number (L), e.g. between 1 and 6. Checking that it was Uncle Bob who signed the transaction, otherwise we reject the impostor transactionOur algorithms are very simple and understandable even to the average Internet user and do not need additional explanationCoin game algorithm | function confirm(bytes32 seed, uint8 _v, bytes32 _r, bytes32 _s) public onlyCroupier {
require (ecrecover(seed, _v, _r, _s) == CROUPIER_BOB);
Game storage game = listGames[seed];
bytes memory choice = game.choice;
game.result = uint256(_s) % 12;
uint profit = 0;
uint8 user_choice;
if (game.game_title == Games.CoinFlip){
if(game.result == user_choice){
profit = game.bet.mul(WIN_COEFFICIENT).div(100);
game.state = GameState.Win;
game.profit = profit;
game.player.transfer(profit);
emit ConfirmGame(game.player, 'CoinFlip', profit, game.choice, game.result, game.seed, true, false, now);
game.state = GameState.Lose;
emit ConfirmGame(game.player, 'CoinFlip', 0, game.choice, game.result, game.seed, false, false, now);
}
if(game.result != user_choice){
if (user_choice == 1 && game.result == 2 || user_choice == 2 && game.result == 3 || user_choice == 3 && game.result == 1) {
profit = game.bet.mul(WIN_COEFFICIENT).div(100);
game.state = GameState.Win;
game.profit = profit;
game.player.transfer(profit);
emit ConfirmGame(game.player, 'KNB', profit, game.choice, game.result, game.seed, true, false, now);
game.state = GameState.Lose;
emit ConfirmGame(game.player, 'KNB', 0, game.choice, game.result, game.seed, false, false, now);
}
profit = game.bet.sub(0.001 ether);
game.player.transfer(profit);
game.state = GameState.Draw;
emit ConfirmGame(game.player, 'KNB', profit, game.choice, game.result, game.seed, false, true, now);
}
uint length = game.choice.length + 1;
for(uint8 i=1; i< length; i++){
if (user_choice == game.result){
profit = game.bet.mul(DICE_COEFFICIENT.div(game.choice.length)).div(100);
}
}
if(profit > 0){
game.state = GameState.Win;
game.profit = profit;
game.player.transfer(profit);
emit ConfirmGame(game.player, 'Dice', profit, game.choice, game.result, game.seed, true, false, now);
game.state = GameState.Lose;
emit ConfirmGame(game.player, 'Dice', 0, game.choice, game.result, game.seed, false, false, now);
}
}
}
| 12,980,995 |
pragma solidity ^0.4.23;
/* all this file is based on code from open zepplin
* https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/token */
/**
* Standard ERC20 token
*
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
require(b > 0);
uint c = a / b;
require(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint 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;
}
}
////////////////////////////////////////////////////////////////////////////////
/*
* ERC20Basic
* Simpler version of ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function transfer(address _to, uint _value) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint value);
}
////////////////////////////////////////////////////////////////////////////////
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint);
function transferFrom(address from, address to, uint value) public returns(bool);
function approve(address spender, uint value) public returns(bool);
event Approval(address indexed owner, address indexed spender, uint value);
}
////////////////////////////////////////////////////////////////////////////////
/*
* Basic token
* Basic version of StandardToken, with no allowances
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/*
* Fix for the ERC20 short address attack
*/
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
success = true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
}
////////////////////////////////////////////////////////////////////////////////
/**
* Standard ERC20 token
*
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
uint _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already revert if this condition is not met
if (_value > _allowance) revert();
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
}
////////////////////////////////////////////////////////////////////////////////
/*
* SimpleToken
*
* Very simple ERC20 Token example, where all tokens are pre-assigned
* to the creator. Note they can later distribute these tokens
* as they wish using `transfer` and other `StandardToken` functions.
*/
contract TestToken is StandardToken {
string public name = "Test";
string public symbol = "TST";
uint public decimals = 18;
uint public INITIAL_SUPPLY = 10**(50+18);
constructor(string _name, string _symbol, uint _decimals) public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
event Burn(address indexed _burner, uint _value);
function burn(uint _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0x0), _value);
return true;
}
// save some gas by making only one contract call
function burnFrom(address _from, uint256 _value) public returns (bool) {
transferFrom(_from, msg.sender, _value);
return burn(_value);
}
}
| Check is not needed because sub(_allowance, _value) will already revert if this condition is not met | function transferFrom(address _from, address _to, uint _value) public returns (bool) {
uint _allowance = allowed[_from][msg.sender];
if (_value > _allowance) revert();
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| 12,854,133 |
./full_match/4/0x75716Ca83c93c9b6fBbf2481bCF2aF72A225098E/sources/contracts/AnniversaryAchievement.sol | Change campaignId Only callable by owner. _campaignId: campaign id/ | function changeCampaignId(uint256 _campaignId) external onlyOwner {
campaignId = _campaignId;
emit NewCampaignId(_campaignId);
}
| 647,258 |
/**
*Submitted for verification at Etherscan.io on 2022-04-28
*/
pragma solidity ^0.8.9;
// SPDX-License-Identifier: NONE
//
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
//
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
/**
* @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);
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.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;
address private immutable _CACHED_THIS;
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);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && 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);
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
/**
* @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;
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.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();
}
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
/**
* @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);
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Arrays.sol)
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Snapshot.sol)
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it
* return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this
* function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract.
*
* Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient
* alternative consider {ERC20Votes}.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping(address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _getCurrentSnapshotId();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Get the current snapshotId
*/
function _getCurrentSnapshotId() internal view virtual returns (uint256) {
return _currentSnapshotId.current();
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// Update balance and/or total supply snapshots before the values are modified. This is implemented
// in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
// mint
_updateAccountSnapshot(to);
_updateTotalSupplySnapshot();
} else if (to == address(0)) {
// burn
_updateAccountSnapshot(from);
_updateTotalSupplySnapshot();
} else {
// transfer
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
}
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) {
require(snapshotId > 0, "ERC20Snapshot: id is 0");
require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _getCurrentSnapshotId();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
// 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 generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for 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");
}
}
}
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;
}
//
// QuickFarm V1
// CREATED FOR MUSK GOLD BY QUICKFARM
contract MuskGoldFarmV1 is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////
// USER DEPOSIT DEFINITION
//////////////////////////////////////////
struct UserDeposit {
uint256 balance; // THE DEPOSITED NUMBER OF TOKENS BY THE USER
uint256 unlockTime; // TIME WHEN THE USER CAN WITHDRAW FUNDS (BASED ON EPOCH)
uint256 lastPayout; // BLOCK NUMBER OF THE LAST PAYOUT FOR THIS USER IN THIS POOL
uint256 totalEarned; // TOTAL NUMBER OF TOKENS THIS USER HAS EARNED
}
//////////////////////////////////////////
// REWARD POOL DEFINITION
//////////////////////////////////////////
struct RewardPool {
IERC20 depositToken; // ADDRESS OF DEPOSITED TOKEN CONTRACT
bool active; // DETERMINES WHETHER OR NOT THIS POOL IS USABLE
bool hidden; // FLAG FOR WHETHER UI SHOULD RENDER THIS
bool uniV2Lp; // SIGNIFIES A IUNISWAPV2PAIR
bool selfStake; // SIGNIFIES IF THIS IS A 'SINGLE SIDED' SELF STAKE
bytes32 lpOrigin; // ORIGIN OF LP TOKEN BEING DEPOSITED E.G. SUSHI, UNISWAP, PANCAKE - NULL IF NOT N LP TOKEN
uint256 lockSeconds; // HOW LONG UNTIL AN LP DEPOSIT CAN BE REMOVED IN SECONDS
bool lockEnforced; // DETERMINES WHETER TIME LOCKS ARE ENFORCED
uint256 rewardPerBlock; // HOW MANY TOKENS TO REWARD PER BLOCK FOR THIS POOL
bytes32 label; // TEXT LABEL STRICTLY FOR READABILITY AND RENDERING
bytes32 order; // DISPLAY/PRESENTATION ORDER OF THE POOL
uint256 depositSum; // SUM OF ALL DEPOSITED TOKENS IN THIS POOL
}
//////////////////////////////////////////
// USER FARM STATE DEFINITION
//////////////////////////////////////////
struct UserFarmState {
RewardPool[] pools; // REWARD POOLS
uint256[] balance; // DEPOSITS BY POOL
uint256[] unlockTime; // UNLOCK TIME FOR EACH POOL DEPOSIT
uint256[] pending; // PENDING REWARDS BY POOL
uint256[] earnings; // EARNINGS BY POOL
uint256[] depTknBal; // USER BALANCE OF DEPOSIT TOKEN
uint256[] depTknSupply; // TOTAL SUPPLY OF DEPOSIT TOKEN
uint256[] reserve0; // RESERVE0 AMOUNT FOR LP TKN0
uint256[] reserve1; // RESERVE1 AMOUNT FOR LP TKN1
address[] token0; // ADDRESS OF LP TOKEN 0
address[] token1; // ADDRESS OF LP TOKEN 1
uint256 rewardTknBal; // CURRENT USER HOLDINGS OF THE REWARD TOKEN
uint256 pendingAllPools; // REWARDS PENDING FOR ALL POOLS
uint256 earningsAllPools; // REWARDS EARNED FOR ALL POOLS
}
//////////////////////////////////////////
// INIT CLASS VARIABLES
//////////////////////////////////////////
bytes32 public name; // POOL NAME, FOR DISPLAY ON BLOCK EXPLORER
IERC20 public rewardToken; // ADDRESS OF THE ERC20 REWARD TOKEN
address public rewardWallet; // WALLE THAT REWARD TOKENS ARE DRAWN FROM
uint256 public earliestRewards; // EARLIEST BLOCK REWARDS CAN BE GENERATED FROM (FOR FAIR LAUNCH)
uint256 public paidOut = 0; // TOTAL AMOUNT OF REWARDS THAT HAVE BEEN PAID OUT
RewardPool[] public rewardPools; // INFO OF EACH POOL
address[] public depositAddresses; // LIST OF ADDRESSES THAT CURRENTLY HAVE FUNDS DEPOSITED
mapping(uint256 => mapping(address => UserDeposit)) public userDeposits; // INFO OF EACH USER THAT STAKES LP TOKENS
//////////////////////////////////////////
// EVENTS
//////////////////////////////////////////
event Deposit(
address indexed from,
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Reward(address indexed user, uint256 indexed pid, uint256 amount);
event Restake(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
//////////////////////////////////////////
// CONSTRUCTOR
//////////////////////////////////////////
constructor(
IERC20 _rewardToken,
address _rewardWallet,
uint256 _earliestRewards
) {
name = "Musk Gold Farm";
rewardToken = _rewardToken;
rewardWallet = _rewardWallet;
earliestRewards = _earliestRewards;
}
//////////////////////////////////////////
// FARM FUNDING CONTROLS
//////////////////////////////////////////
// SETS ADDRESS THAT REWARDS ARE TO BE PAID FROM
function setRewardWallet(address _source) external onlyOwner {
rewardWallet = _source;
}
// FUND THE FARM (JUST DEPOSITS FUNDS INTO THE REWARD WALLET)
function fund(uint256 _amount) external {
require(msg.sender != rewardWallet, "Sender is reward wallet");
rewardToken.safeTransferFrom(
address(msg.sender),
rewardWallet,
_amount
);
}
//////////////////////////////////////////
// POOL CONTROLS
//////////////////////////////////////////
// ADD LP TOKEN REWARD POOL
function addPool(
IERC20 _depositToken,
bool _active,
bool _hidden,
bool _uniV2Lp,
bytes32 _lpOrigin,
uint256 _lockSeconds,
bool _lockEnforced,
uint256 _rewardPerBlock,
bytes32 _label,
bytes32 _order
) external onlyOwner {
// MAKE SURE THIS REWARD POOL FOR TOKEN + LOCK DOESN'T ALREADY EXIST
require(
poolExists(_depositToken, _lockSeconds) == false,
"Reward pool for token already exists"
);
// IF TOKEN BEING DEPOSITED IS THE SAME AS THE REWARD TOKEN MARK IT AS A SELF STAKE (SINGLE SIDED)
bool selfStake = false;
if (_depositToken == rewardToken) {
selfStake = true;
_uniV2Lp = false;
}
rewardPools.push(
RewardPool({
depositToken: _depositToken,
active: _active,
hidden: _hidden,
uniV2Lp: _uniV2Lp,
selfStake: selfStake, // MARKS IF A "SINGLED SIDED" STAKE OF THE REWARD TOKEN
lpOrigin: _lpOrigin,
lockSeconds: _lockSeconds,
lockEnforced: _lockEnforced,
rewardPerBlock: _rewardPerBlock,
label: _label,
order: _order,
depositSum: 0
})
);
}
function setPool(
// MODIFY AN EXISTING POOL
uint256 _pid,
bool _active,
bool _hidden,
bool _uniV2Lp,
bytes32 _lpOrigin,
uint256 _lockSeconds,
bool _lockEnforced,
uint256 _rewardPerBlock,
bytes32 _label,
bytes32 _order
) external onlyOwner {
rewardPools[_pid].active = _active;
rewardPools[_pid].hidden = _hidden;
rewardPools[_pid].uniV2Lp = _uniV2Lp;
rewardPools[_pid].lpOrigin = _lpOrigin;
rewardPools[_pid].lockSeconds = _lockSeconds;
rewardPools[_pid].lockEnforced = _lockEnforced;
rewardPools[_pid].rewardPerBlock = _rewardPerBlock;
rewardPools[_pid].label = _label;
rewardPools[_pid].order = _order;
}
// PAUSES/RESUMES DEPOSITS FOR ALL POOLS
function setFarmActive(bool _value) public onlyOwner {
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
RewardPool storage pool = rewardPools[pid];
pool.active = _value;
}
}
// SETS THE EARLIEST BLOCK FROM WHICH TO CALCULATE REWARDS
function setEarliestRewards(uint256 _value) external onlyOwner {
require(
_value >= block.number,
"Earliest reward block must be greater than the current block"
);
earliestRewards = _value;
}
//////////////////////////////////////////
// DEPOSIT/WITHDRAW METHODS
//////////////////////////////////////////
// SETS THE "LAST PAYOUT" FOR A USER TO ULTIMATELY DETERMINE HOW MANY REWARDS THEY ARE OWED
function setLastPayout(UserDeposit storage _deposit) private {
_deposit.lastPayout = block.number;
if (_deposit.lastPayout < earliestRewards)
_deposit.lastPayout = earliestRewards; // FAIR LAUNCH ACCOMODATION
}
// DEPOSIT TOKENS (LP OR SIMPLE ERC20) FOR A GIVEN TARGET (USER) WALLET
function deposit(
uint256 _pid,
address _user,
uint256 _amount
) public nonReentrant {
RewardPool storage pool = rewardPools[_pid];
require(_amount > 0, "Amount must be greater than zero");
require(pool.active == true, "This reward pool is inactive");
UserDeposit storage userDeposit = userDeposits[_pid][_user];
// SET INITIAL LAST PAYOUT
if (userDeposit.lastPayout == 0) {
userDeposit.lastPayout = block.number;
if (userDeposit.lastPayout < earliestRewards)
userDeposit.lastPayout = earliestRewards; // FAIR LAUNCH ACCOMODATION
}
// COLLECT REWARD ONLY IF ADDRESS DEPOSITING IS THE OWNER OF THE DEPOSIT
if (userDeposit.balance > 0 && msg.sender == _user) {
payReward(_pid, _user);
}
pool.depositToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
); // DO THE ACTUAL DEPOSIT
userDeposit.balance = userDeposit.balance.add(_amount); // ADD THE TRANSFERRED AMOUNT TO THE DEPOSIT VALUE
userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // UPDATE THE UNLOCK TIME
pool.depositSum = pool.depositSum.add(_amount); // KEEP TRACK OF TOTAL DEPOSITS IN THE POOL
recordAddress(_user); // RECORD THE USER ADDRESS IN THE LIST
emit Deposit(msg.sender, _user, _pid, _amount);
}
// PRIVATE METHOD TO PAY OUT USER REWARDS
function payReward(uint256 _pid, address _user) private {
UserDeposit storage userDeposit = userDeposits[_pid][_user]; // FETCH THE DEPOSIT
uint256 rewardsDue = userPendingPool(_pid, _user); // GET PENDING REWARDS
if (rewardsDue <= 0) return; // BAIL OUT IF NO REWARD IS DUE
rewardToken.transferFrom(rewardWallet, _user, rewardsDue);
emit Reward(_user, _pid, rewardsDue);
userDeposit.totalEarned = userDeposit.totalEarned.add(rewardsDue); // ADD THE PAYOUT AMOUNT TO TOTAL EARNINGS
paidOut = paidOut.add(rewardsDue); // ADD AMOUNT TO TOTAL PAIDOUT FOR THE WHOLE FARM
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
}
// EXTERNAL METHOD FOR USER'S TO COLLECT REWARDS
function collectReward(uint256 _pid) external nonReentrant {
payReward(_pid, msg.sender);
}
// RESTAKE REWARDS INTO SINGLE-SIDED POOLS
function restake(uint256 _pid) external nonReentrant {
RewardPool storage pool = rewardPools[_pid]; // GET THE POOL
UserDeposit storage userDeposit = userDeposits[_pid][msg.sender]; // FETCH THE DEPOSIT
require(
pool.depositToken == rewardToken,
"Restake is only available on single-sided staking"
);
uint256 rewardsDue = userPendingPool(_pid, msg.sender); // GET PENDING REWARD AMOUNT
if (rewardsDue <= 0) return; // BAIL OUT IF NO REWARDS ARE TO BE PAID
pool.depositToken.safeTransferFrom(
rewardWallet,
address(this),
rewardsDue
); // MOVE FUNDS FROM THE REWARDS TO THIS CONTRACT
pool.depositSum = pool.depositSum.add(rewardsDue);
userDeposit.balance = userDeposit.balance.add(rewardsDue); // ADD THE FUNDS MOVED TO THE USER'S BALANCE
userDeposit.totalEarned = userDeposit.totalEarned.add(rewardsDue); // ADD FUNDS MOVED TO USER'S TOTAL EARNINGS FOR POOL
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
paidOut = paidOut.add(rewardsDue); // ADD TO THE TOTAL PAID OUT FOR THE FARM
emit Restake(msg.sender, _pid, rewardsDue);
}
// WITHDRAW LP TOKENS FROM FARM.
function withdraw(uint256 _pid, uint256 _amount) external nonReentrant {
RewardPool storage pool = rewardPools[_pid];
UserDeposit storage userDeposit = userDeposits[_pid][msg.sender];
if (pool.lockEnforced)
require(
userDeposit.unlockTime <= block.timestamp,
"withdraw: time lock has not passed"
);
require(
userDeposit.balance >= _amount,
"withdraw: can't withdraw more than deposit"
);
payReward(_pid, msg.sender); // PAY OUT ANY REWARDS ACCUMULATED UP TO THIS POINT
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // RESET THE UNLOCK TIME
userDeposit.balance = userDeposit.balance.sub(_amount); // SUBTRACT THE AMOUNT DEBITED FROM THE BALANCE
pool.depositToken.safeTransfer(address(msg.sender), _amount); // TRANSFER THE WITHDRAWN AMOUNT BACK TO THE USER
emit Withdraw(msg.sender, _pid, _amount);
pool.depositSum = pool.depositSum.sub(_amount); // SUBTRACT THE WITHDRAWN AMOUNT FROM THE POOL DEPOSIT TOTAL
cleanupAddress(msg.sender);
}
// APPEND ADDRESSES THAT HAVE FUNDS DEPOSITED FOR EASY RETRIEVAL
function recordAddress(address _address) private {
for (uint256 i = 0; i < depositAddresses.length; i++) {
address curAddress = depositAddresses[i];
if (_address == curAddress) return;
}
depositAddresses.push(_address);
}
// CLEAN ANY ADDRESSES THAT DON'T HAVE ACTIVE DEPOSITS
function cleanupAddress(address _address) private {
// CHECK TO SEE IF THE ADDRESS HAS ANY DEPOSITS
uint256 deposits = 0;
for (uint256 pid = 0; pid < rewardPools.length; pid++) {
deposits = deposits.add(userDeposits[pid][_address].balance);
}
if (deposits > 0) return; // BAIL OUT IF USER STILL HAS DEPOSITS
for (uint256 i = 0; i < depositAddresses.length; i++) {
address curAddress = depositAddresses[i];
if (_address == curAddress) delete depositAddresses[i]; // REMOVE ADDRESS FROM ARRAY
}
}
//////////////////////////////////////////
// INFORMATION METHODS
//////////////////////////////////////////
// RETURNS THE ARRAY OF POOLS
function getPools() public view returns (RewardPool[] memory) {
return rewardPools;
}
// RETURNS REWARD TOKENS REMAINING
function rewardsRemaining() public view returns (uint256) {
return rewardToken.balanceOf(rewardWallet);
}
// RETURNS COUNT OF ADDRESSES WITH DEPOSITS
function addressCount() external view returns (uint256) {
return depositAddresses.length;
}
// CHECK IF A GIVEN DEPOSIT TOKEN + TIMELOCK COMBINATION ALREADY EXISTS
function poolExists(IERC20 _depositToken, uint256 _lockSeconds)
private
view
returns (bool)
{
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
RewardPool storage pool = rewardPools[pid];
if (
pool.depositToken == _depositToken &&
pool.lockSeconds == _lockSeconds
) return true;
}
return false;
}
// RETURNS COUNT OF LP POOLS
function poolLength() external view returns (uint256) {
return rewardPools.length;
}
// RETURNS SUM OF DEPOSITS IN X POOL
function poolDepositSum(uint256 _pid) external view returns (uint256) {
return rewardPools[_pid].depositSum;
}
// VIEW FUNCTION TO SEE PENDING REWARDS FOR A USER
function userPendingPool(uint256 _pid, address _user)
public
view
returns (uint256)
{
RewardPool storage pool = rewardPools[_pid];
UserDeposit storage userDeposit = userDeposits[_pid][_user];
if (userDeposit.balance == 0) return 0;
if (earliestRewards > block.number) return 0;
uint256 precision = 1e36;
uint256 blocksElapsed = 0;
if (block.number > userDeposit.lastPayout)
blocksElapsed = block.number.sub(userDeposit.lastPayout);
uint256 poolOwnership = userDeposit.balance.mul(precision).div(
pool.depositSum
);
uint256 rewardsDue = blocksElapsed
.mul(pool.rewardPerBlock)
.mul(poolOwnership)
.div(precision);
return rewardsDue;
}
// GETS PENDING REWARDS FOR A GIVEN USER IN ALL POOLS
function userPendingAll(address _user) public view returns (uint256) {
uint256 totalReward = 0;
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
uint256 pending = userPendingPool(pid, _user);
totalReward = totalReward.add(pending);
}
return totalReward;
}
// RETURNS TOTAL PAID OUT TO A USER FOR A GIVEN POOL
function userEarnedPool(uint256 _pid, address _user)
public
view
returns (uint256)
{
return userDeposits[_pid][_user].totalEarned;
}
// RETURNS USER EARNINGS FOR ALL POOLS
function userEarnedAll(address _user) public view returns (uint256) {
uint256 totalEarned = 0;
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
totalEarned = totalEarned.add(userDeposits[pid][_user].totalEarned);
}
return totalEarned;
}
// VIEW FUNCTION FOR TOTAL REWARDS THE FARM HAS YET TO PAY OUT
function farmTotalPending() external view returns (uint256) {
uint256 pending = 0;
for (uint256 i = 0; i < depositAddresses.length; ++i) {
uint256 userPending = userPendingAll(depositAddresses[i]);
pending = pending.add(userPending);
}
return pending;
}
// RETURNS A GIVEN USER'S STATE IN THE FARM IN A SINGLE CALL
function getUserState(address _user)
external
view
returns (UserFarmState memory)
{
uint256[] memory balance = new uint256[](rewardPools.length);
uint256[] memory pending = new uint256[](rewardPools.length);
uint256[] memory earned = new uint256[](rewardPools.length);
uint256[] memory depTknBal = new uint256[](rewardPools.length);
uint256[] memory depTknSupply = new uint256[](rewardPools.length);
uint256[] memory depTknReserve0 = new uint256[](rewardPools.length);
uint256[] memory depTknReserve1 = new uint256[](rewardPools.length);
address[] memory depTknResTkn0 = new address[](rewardPools.length);
address[] memory depTknResTkn1 = new address[](rewardPools.length);
uint256[] memory unlockTime = new uint256[](rewardPools.length);
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
balance[pid] = userDeposits[pid][_user].balance;
pending[pid] = userPendingPool(pid, _user);
earned[pid] = userEarnedPool(pid, _user);
depTknBal[pid] = rewardPools[pid].depositToken.balanceOf(_user);
depTknSupply[pid] = rewardPools[pid].depositToken.totalSupply();
unlockTime[pid] = userDeposits[pid][_user].unlockTime;
if (
rewardPools[pid].uniV2Lp == true &&
rewardPools[pid].selfStake == false
) {
IUniswapV2Pair pair = IUniswapV2Pair(
address(rewardPools[pid].depositToken)
);
(uint256 res0, uint256 res1, uint256 timestamp) = pair
.getReserves();
depTknReserve0[pid] = res0;
depTknReserve1[pid] = res1;
depTknResTkn0[pid] = pair.token0();
depTknResTkn1[pid] = pair.token1();
}
}
return
UserFarmState(
rewardPools, // POOLS
balance, // DEPOSITS BY POOL
unlockTime, // UNLOCK TIME FOR EACH DEPOSITED POOL
pending, // PENDING REWARDS BY POOL
earned, // EARNINGS BY POOL
depTknBal, // USER BALANCE OF DEPOSIT TOKEN
depTknSupply, // TOTAL SUPPLY OF DEPOSIT TOKEN
depTknReserve0, // RESERVE0 AMOUNT FOR LP TKN0
depTknReserve1, // RESERVE1 AMOUNT FOR LP TKN1
depTknResTkn0, // ADDRESS OF LP TOKEN 0
depTknResTkn1, // ADDRESS OF LP TOKEN 1
rewardToken.balanceOf(_user), // CURRENT USER HOLDINGS OF THE REWARD TOKEN
userPendingAll(_user), // REWARDS PENDING FOR ALL POOLS
userEarnedAll(_user) // REWARDS EARNED FOR ALL POOLS
);
}
//////////////////////////////////////////
// EMERGENCY CONTROLS
//////////////////////////////////////////
// WITHDRAW WITHOUT CARING ABOUT REWARDS. EMERGENCY ONLY.
// THIS WILL WIPE OUT ANY PENDING REWARDS FOR A USER
function emergencyWithdraw(uint256 _pid) external nonReentrant {
RewardPool storage pool = rewardPools[_pid]; // GET THE POOL
UserDeposit storage userDeposit = userDeposits[_pid][msg.sender]; //GET THE DEPOSIT
pool.depositToken.safeTransfer(
address(msg.sender),
userDeposit.balance
); // TRANSFER THE DEPOSIT BACK TO THE USER
pool.depositSum = pool.depositSum.sub(userDeposit.balance); // DECREMENT THE POOL'S OVERALL DEPOSIT SUM
userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // RESET THE UNLOCK TIME
userDeposit.balance = 0; // SET THE BALANCE TO ZERO AFTER WIRTHDRAWAL
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
emit EmergencyWithdraw(msg.sender, _pid, userDeposit.balance);
}
} | EXTERNAL METHOD FOR USER'S TO COLLECT REWARDS | function collectReward(uint256 _pid) external nonReentrant {
payReward(_pid, msg.sender);
}
| 7,938,610 |
pragma solidity = 0.5.16;
import "./IKyber.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
contract KyberAdapter {
using SafeMath for uint256;
IKyber public kyber;
ERC20 public ETH_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
constructor(address _kyberProxy) public {
kyber = IKyber(_kyberProxy);
}
function () external payable {}
function _getTokenDecimals(ERC20 _token) internal view returns (uint8 _decimals) {
return _token != ETH_ADDRESS ? ERC20Detailed(address(_token)).decimals() : 18;
}
function _getTokenBalance(ERC20 _token, address _account) internal view returns (uint256 _balance) {
return _token != ETH_ADDRESS ? _token.balanceOf(_account) : _account.balance;
}
function ceilingDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {
return a.div(b).add(a.mod(b) > 0 ? 1 : 0);
}
function _fixTokenDecimals(
ERC20 _src,
ERC20 _dest,
uint256 _unfixedDestAmount,
bool _ceiling
)
internal
view
returns (uint256 _destTokenAmount)
{
uint256 _unfixedDecimals = _getTokenDecimals(_src) + 18; // Kyber by default returns rates with 18 decimals.
uint256 _decimals = _getTokenDecimals(_dest);
if (_unfixedDecimals > _decimals) {
// Divide token amount by 10^(_unfixedDecimals - _decimals) to reduce decimals.
if (_ceiling) {
return ceilingDiv(_unfixedDestAmount, (10 ** (_unfixedDecimals - _decimals)));
} else {
return _unfixedDestAmount.div(10 ** (_unfixedDecimals - _decimals));
}
} else {
// Multiply token amount with 10^(_decimals - _unfixedDecimals) to increase decimals.
return _unfixedDestAmount.mul(10 ** (_decimals - _unfixedDecimals));
}
}
function _convertToken(
ERC20 _src,
uint256 _srcAmount,
ERC20 _dest
)
internal
view
returns (
uint256 _expectedAmount,
uint256 _slippageAmount
)
{
(uint256 _expectedRate, uint256 _slippageRate) = kyber.getExpectedRate(_src, _dest, _srcAmount);
return (
_fixTokenDecimals(_src, _dest, _srcAmount.mul(_expectedRate), false),
_fixTokenDecimals(_src, _dest, _srcAmount.mul(_slippageRate), false)
);
}
function _swapTokenAndHandleChange(
ERC20 _src,
uint256 _maxSrcAmount,
ERC20 _dest,
uint256 _maxDestAmount,
uint256 _minConversionRate,
address payable _initiator,
address payable _receiver
)
internal
returns (
uint256 _srcAmount,
uint256 _destAmount
)
{
if (_src == _dest) {
// payment is made with DAI
require(_maxSrcAmount >= _maxDestAmount);
_destAmount = _srcAmount = _maxDestAmount;
require(IERC20(_src).transferFrom(_initiator, address(this), _destAmount));
} else {
require(_src == ETH_ADDRESS ? msg.value >= _maxSrcAmount : msg.value == 0);
// Prepare for handling back the change if there is any.
uint256 _balanceBefore = _getTokenBalance(_src, address(this));
if (_src != ETH_ADDRESS) {
require(IERC20(_src).transferFrom(_initiator, address(this), _maxSrcAmount));
require(IERC20(_src).approve(address(kyber), _maxSrcAmount));
} else {
// Since we are going to transfer the source amount to Kyber.
_balanceBefore = _balanceBefore.sub(_maxSrcAmount);
}
_destAmount = kyber.trade.value(
_src == ETH_ADDRESS ? _maxSrcAmount : 0
)(
_src,
_maxSrcAmount,
_dest,
_receiver,
_maxDestAmount,
_minConversionRate,
address(0)
);
uint256 _balanceAfter = _getTokenBalance(_src, address(this));
_srcAmount = _maxSrcAmount;
// Handle back the change, if there is any, to the message sender.
if (_balanceAfter > _balanceBefore) {
uint256 _change = _balanceAfter - _balanceBefore;
_srcAmount = _srcAmount.sub(_change);
if (_src != ETH_ADDRESS) {
require(IERC20(_src).transfer(_initiator, _change));
} else {
_initiator.transfer(_change);
}
}
}
}
} | payment is made with DAI Prepare for handling back the change if there is any. Since we are going to transfer the source amount to Kyber. Handle back the change, if there is any, to the message sender. | function _swapTokenAndHandleChange(
ERC20 _src,
uint256 _maxSrcAmount,
ERC20 _dest,
uint256 _maxDestAmount,
uint256 _minConversionRate,
address payable _initiator,
address payable _receiver
)
internal
returns (
uint256 _srcAmount,
uint256 _destAmount
)
{
if (_src == _dest) {
require(_maxSrcAmount >= _maxDestAmount);
_destAmount = _srcAmount = _maxDestAmount;
require(IERC20(_src).transferFrom(_initiator, address(this), _destAmount));
require(_src == ETH_ADDRESS ? msg.value >= _maxSrcAmount : msg.value == 0);
uint256 _balanceBefore = _getTokenBalance(_src, address(this));
if (_src != ETH_ADDRESS) {
require(IERC20(_src).transferFrom(_initiator, address(this), _maxSrcAmount));
require(IERC20(_src).approve(address(kyber), _maxSrcAmount));
_balanceBefore = _balanceBefore.sub(_maxSrcAmount);
}
_destAmount = kyber.trade.value(
_src == ETH_ADDRESS ? _maxSrcAmount : 0
)(
_src,
_maxSrcAmount,
_dest,
_receiver,
_maxDestAmount,
_minConversionRate,
address(0)
);
uint256 _balanceAfter = _getTokenBalance(_src, address(this));
_srcAmount = _maxSrcAmount;
if (_balanceAfter > _balanceBefore) {
uint256 _change = _balanceAfter - _balanceBefore;
_srcAmount = _srcAmount.sub(_change);
if (_src != ETH_ADDRESS) {
require(IERC20(_src).transfer(_initiator, _change));
_initiator.transfer(_change);
}
}
}
}
| 7,233,121 |
./full_match/43113/0x78Dd414DF1fC487B5123314a17685D1dF34ff670/sources/project_/contracts/Fold.sol | mint the $Fold to the TWENTY contract upon NFT creation _amount amount to mint/ | function mintStakingShare(uint _amount) external onlyOwner {
uint256 realAmount = _amount*FOLD_TOKEN_PRECISION;
if(realAmount + totalSupply() > MAX_SUPPLY){
revert("Tokens all allocated");
}
_mint(address(foldStaking), realAmount);
}
| 7,113,677 |
pragma solidity ^0.4.17;
// File: contracts/iERC20Token.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ConsenSys/Tokens
// https://github.com/ethereum/EIPs/issues/20
pragma solidity ^0.4.17;
/// @title iERC20Token contract
contract iERC20Token {
// FIELDS
uint256 public totalSupply = 0;
bytes32 public name;// token name, e.g, pounds for fiat UK pounds.
uint8 public decimals;// How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
bytes32 public symbol;// An identifier: eg SBX.
// NON-CONSTANT METHODS
/// @dev send `_value` tokens to `_to` address/wallet from `msg.sender`.
/// @param _to The address of the recipient.
/// @param _value The amount of token to be transferred.
/// @return Whether the transfer was successful or not.
function transfer(address _to, uint256 _value) public returns (bool success);
/// @dev send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @dev `msg.sender` approves `_spender` to spend `_value` tokens.
/// @param _spender The address of the account able to transfer the tokens.
/// @param _value The amount of tokens to be approved for transfer.
/// @return Whether the approval was successful or not.
function approve(address _spender, uint256 _value) public returns (bool success);
// CONSTANT METHODS
/** @dev Checks the balance of an address without changing the state of the blockchain.
* @param _owner The address to check.
* @return balance An unsigned integer representing the token balance of the address.
*/
function balanceOf(address _owner) public view returns (uint256 balance);
/** @dev Checks for the balance of the tokens of that which the owner had approved another address owner to spend.
* @param _owner The address of the token owner.
* @param _spender The address of the allowed spender.
* @return remaining An unsigned integer representing the remaining approved tokens.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// An event triggered when a transfer of tokens is made from a _from address to a _to address.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// An event triggered when an owner of tokens successfully approves another address to spend a specified amount of tokens.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// File: contracts/CurrencyToken.sol
/// @title CurrencyToken contract
contract CurrencyToken {
address public server; // Address, which the platform website uses.
address public populous; // Address of the Populous bank contract.
uint256 public totalSupply;
bytes32 public name;// token name, e.g, pounds for fiat UK pounds.
uint8 public decimals;// How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
bytes32 public symbol;// An identifier: eg SBX.
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
//EVENTS
// An event triggered when a transfer of tokens is made from a _from address to a _to address.
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
// An event triggered when an owner of tokens successfully approves another address to spend a specified amount of tokens.
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
event EventMintTokens(bytes32 currency, address owner, uint amount);
event EventDestroyTokens(bytes32 currency, address owner, uint amount);
// MODIFIERS
modifier onlyServer {
require(isServer(msg.sender) == true);
_;
}
modifier onlyServerOrOnlyPopulous {
require(isServer(msg.sender) == true || isPopulous(msg.sender) == true);
_;
}
modifier onlyPopulous {
require(isPopulous(msg.sender) == true);
_;
}
// NON-CONSTANT METHODS
/** @dev Creates a new currency/token.
* param _decimalUnits The decimal units/places the token can have.
* param _tokenSymbol The token's symbol, e.g., GBP.
* param _decimalUnits The tokens decimal unites/precision
* param _amount The amount of tokens to create upon deployment
* param _owner The owner of the tokens created upon deployment
* param _server The server/admin address
*/
function CurrencyToken ()
public
{
populous = server = 0xf8B3d742B245Ec366288160488A12e7A2f1D720D;
symbol = name = 0x55534443; // Set the name for display purposes
decimals = 6; // Amount of decimals for display purposes
balances[server] = safeAdd(balances[server], 10000000000000000);
totalSupply = safeAdd(totalSupply, 10000000000000000);
}
// ERC20
/** @dev Mints a specified amount of tokens
* @param owner The token owner.
* @param amount The amount of tokens to create.
*/
function mint(uint amount, address owner) public onlyServerOrOnlyPopulous returns (bool success) {
balances[owner] = safeAdd(balances[owner], amount);
totalSupply = safeAdd(totalSupply, amount);
emit EventMintTokens(symbol, owner, amount);
return true;
}
/** @dev Destroys a specified amount of tokens
* @dev The method uses a modifier from withAccessManager contract to only permit populous to use it.
* @dev The method uses SafeMath to carry out safe token deductions/subtraction.
* @param amount The amount of tokens to create.
*/
function destroyTokens(uint amount) public onlyServerOrOnlyPopulous returns (bool success) {
require(balances[msg.sender] >= amount);
balances[msg.sender] = safeSub(balances[msg.sender], amount);
totalSupply = safeSub(totalSupply, amount);
emit EventDestroyTokens(symbol, populous, amount);
return true;
}
/** @dev Destroys a specified amount of tokens, from a user.
* @dev The method uses a modifier from withAccessManager contract to only permit populous to use it.
* @dev The method uses SafeMath to carry out safe token deductions/subtraction.
* @param amount The amount of tokens to create.
*/
function destroyTokensFrom(uint amount, address from) public onlyServerOrOnlyPopulous returns (bool success) {
require(balances[from] >= amount);
balances[from] = safeSub(balances[from], amount);
totalSupply = safeSub(totalSupply, amount);
emit EventDestroyTokens(symbol, from, amount);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// ACCESS MANAGER
/** @dev Checks a given address to determine whether it is populous address.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to populous or not.
*/
function isPopulous(address sender) public view returns (bool) {
return sender == populous;
}
/** @dev Changes the populous contract address.
* @dev The method requires the message sender to be the set server.
* @param _populous The address to be set as populous.
*/
function changePopulous(address _populous) public {
require(isServer(msg.sender) == true);
populous = _populous;
}
// CONSTANT METHODS
/** @dev Checks a given address to determine whether it is the server.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to the server or not.
*/
function isServer(address sender) public view returns (bool) {
return sender == server;
}
/** @dev Changes the server address that is set by the constructor.
* @dev The method requires the message sender to be the set server.
* @param _server The new address to be set as the server.
*/
function changeServer(address _server) public {
require(isServer(msg.sender) == true);
server = _server;
}
// SAFE MATH
/** @dev Safely multiplies two unsigned/non-negative integers.
* @dev Ensures that one of both numbers can be derived from dividing the product by the other.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
/** @dev Safely subtracts one number from another
* @dev Ensures that the number to subtract is lower.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/** @dev Safely adds two unsigned/non-negative integers.
* @dev Ensures that the sum of both numbers is greater or equal to one of both.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
// File: contracts/AccessManager.sol
/// @title AccessManager contract
contract AccessManager {
// FIELDS
// fields that can be changed by constructor and functions
address public server; // Address, which the platform website uses.
address public populous; // Address of the Populous bank contract.
// NON-CONSTANT METHODS
/** @dev Constructor that sets the server when contract is deployed.
* @param _server The address to set as the server.
*/
function AccessManager(address _server) public {
server = _server;
//guardian = _guardian;
}
/** @dev Changes the server address that is set by the constructor.
* @dev The method requires the message sender to be the set server.
* @param _server The new address to be set as the server.
*/
function changeServer(address _server) public {
require(isServer(msg.sender) == true);
server = _server;
}
/** @dev Changes the guardian address that is set by the constructor.
* @dev The method requires the message sender to be the set guardian.
*/
/* function changeGuardian(address _guardian) public {
require(isGuardian(msg.sender) == true);
guardian = _guardian;
} */
/** @dev Changes the populous contract address.
* @dev The method requires the message sender to be the set server.
* @param _populous The address to be set as populous.
*/
function changePopulous(address _populous) public {
require(isServer(msg.sender) == true);
populous = _populous;
}
// CONSTANT METHODS
/** @dev Checks a given address to determine whether it is the server.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to the server or not.
*/
function isServer(address sender) public view returns (bool) {
return sender == server;
}
/** @dev Checks a given address to determine whether it is the guardian.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to the guardian or not.
*/
/* function isGuardian(address sender) public view returns (bool) {
return sender == guardian;
} */
/** @dev Checks a given address to determine whether it is populous address.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to populous or not.
*/
function isPopulous(address sender) public view returns (bool) {
return sender == populous;
}
}
// File: contracts/withAccessManager.sol
/// @title withAccessManager contract
contract withAccessManager {
// FIELDS
AccessManager public AM;
// MODIFIERS
// This modifier uses the isServer method in the AccessManager contract AM to determine
// whether the msg.sender address is server.
modifier onlyServer {
require(AM.isServer(msg.sender) == true);
_;
}
modifier onlyServerOrOnlyPopulous {
require(AM.isServer(msg.sender) == true || AM.isPopulous(msg.sender) == true);
_;
}
// This modifier uses the isGuardian method in the AccessManager contract AM to determine
// whether the msg.sender address is guardian.
/* modifier onlyGuardian {
require(AM.isGuardian(msg.sender) == true);
_;
} */
// This modifier uses the isPopulous method in the AccessManager contract AM to determine
// whether the msg.sender address is populous.
modifier onlyPopulous {
require(AM.isPopulous(msg.sender) == true);
_;
}
// NON-CONSTANT METHODS
/** @dev Sets the AccessManager contract address while deploying this contract`.
* @param _accessManager The address to set.
*/
function withAccessManager(address _accessManager) public {
AM = AccessManager(_accessManager);
}
/** @dev Updates the AccessManager contract address if msg.sender is guardian.
* @param _accessManager The address to set.
*/
function updateAccessManager(address _accessManager) public onlyServer {
AM = AccessManager(_accessManager);
}
}
// File: contracts/ERC1155SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library ERC1155SafeMath {
/**
* @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/Address.sol
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* 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 account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) 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(account) }
return size > 0;
}
}
// File: contracts/IERC1155.sol
/// @dev Note: the ERC-165 identifier for this interface is 0xf23a6e61.
interface IERC1155TokenReceiver {
/// @notice Handle the receipt of an ERC1155 type
/// @dev The smart contract calls this function on the recipient
/// after a `safeTransfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _id The identifier of the item being transferred
/// @param _value The amount of the item being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
/// unless throwing
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes _data) external returns(bytes4);
}
interface IERC1155 {
event Approval(address indexed _owner, address indexed _spender, uint256 indexed _id, uint256 _oldValue, uint256 _value);
event Transfer(address _spender, address indexed _from, address indexed _to, uint256 indexed _id, uint256 _value);
function transferFrom(address _from, address _to, uint256 _id, uint256 _value) external;
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes _data) external;
function approve(address _spender, uint256 _id, uint256 _currentValue, uint256 _value) external;
function balanceOf(uint256 _id, address _owner) external view returns (uint256);
function allowance(uint256 _id, address _owner, address _spender) external view returns (uint256);
}
interface IERC1155Extended {
function transfer(address _to, uint256 _id, uint256 _value) external;
function safeTransfer(address _to, uint256 _id, uint256 _value, bytes _data) external;
}
interface IERC1155BatchTransfer {
function batchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values) external;
function safeBatchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values, bytes _data) external;
function batchApprove(address _spender, uint256[] _ids, uint256[] _currentValues, uint256[] _values) external;
}
interface IERC1155BatchTransferExtended {
function batchTransfer(address _to, uint256[] _ids, uint256[] _values) external;
function safeBatchTransfer(address _to, uint256[] _ids, uint256[] _values, bytes _data) external;
}
interface IERC1155Operators {
event OperatorApproval(address indexed _owner, address indexed _operator, uint256 indexed _id, bool _approved);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function setApproval(address _operator, uint256[] _ids, bool _approved) external;
function isApproved(address _owner, address _operator, uint256 _id) external view returns (bool);
function setApprovalForAll(address _operator, bool _approved) external;
function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator);
}
interface IERC1155Views {
function totalSupply(uint256 _id) external view returns (uint256);
function name(uint256 _id) external view returns (string);
function symbol(uint256 _id) external view returns (string);
function decimals(uint256 _id) external view returns (uint8);
function uri(uint256 _id) external view returns (string);
}
// File: contracts/ERC1155.sol
contract ERC1155 is IERC1155, IERC1155Extended, IERC1155BatchTransfer, IERC1155BatchTransferExtended {
using ERC1155SafeMath for uint256;
using Address for address;
// Variables
struct Items {
string name;
uint256 totalSupply;
mapping (address => uint256) balances;
}
mapping (uint256 => uint8) public decimals;
mapping (uint256 => string) public symbols;
mapping (uint256 => mapping(address => mapping(address => uint256))) public allowances;
mapping (uint256 => Items) public items;
mapping (uint256 => string) public metadataURIs;
bytes4 constant private ERC1155_RECEIVED = 0xf23a6e61;
/////////////////////////////////////////// IERC1155 //////////////////////////////////////////////
// Events
event Approval(address indexed _owner, address indexed _spender, uint256 indexed _id, uint256 _oldValue, uint256 _value);
event Transfer(address _spender, address indexed _from, address indexed _to, uint256 indexed _id, uint256 _value);
function transferFrom(address _from, address _to, uint256 _id, uint256 _value) external {
if(_from != msg.sender) {
//require(allowances[_id][_from][msg.sender] >= _value);
allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
}
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes _data) external {
//this.transferFrom(_from, _to, _id, _value);
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(_from, _to, _id, _value, _data));
if(_from != msg.sender) {
//require(allowances[_id][_from][msg.sender] >= _value);
allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
}
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
function approve(address _spender, uint256 _id, uint256 _currentValue, uint256 _value) external {
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowances[_id][msg.sender][_spender] == _currentValue);
allowances[_id][msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _id, _currentValue, _value);
}
function balanceOf(uint256 _id, address _owner) external view returns (uint256) {
return items[_id].balances[_owner];
}
function allowance(uint256 _id, address _owner, address _spender) external view returns (uint256) {
return allowances[_id][_owner][_spender];
}
/////////////////////////////////////// IERC1155Extended //////////////////////////////////////////
function transfer(address _to, uint256 _id, uint256 _value) external {
// Not needed. SafeMath will do the same check on .sub(_value)
//require(_value <= items[_id].balances[msg.sender]);
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, msg.sender, _to, _id, _value);
}
function safeTransfer(address _to, uint256 _id, uint256 _value, bytes _data) external {
//this.transfer(_to, _id, _value);
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(msg.sender, _to, _id, _value, _data));
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, msg.sender, _to, _id, _value);
}
//////////////////////////////////// IERC1155BatchTransfer ////////////////////////////////////////
function batchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values) external {
uint256 _id;
uint256 _value;
if(_from == msg.sender) {
for (uint256 i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
}
else {
for (i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
}
}
function safeBatchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values, bytes _data) external {
//this.batchTransferFrom(_from, _to, _ids, _values);
for (uint256 i = 0; i < _ids.length; ++i) {
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(_from, _to, _ids[i], _values[i], _data));
}
uint256 _id;
uint256 _value;
if(_from == msg.sender) {
for (i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
}
else {
for (i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
}
}
function batchApprove(address _spender, uint256[] _ids, uint256[] _currentValues, uint256[] _values) external {
uint256 _id;
uint256 _value;
for (uint256 i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
require(_value == 0 || allowances[_id][msg.sender][_spender] == _currentValues[i]);
allowances[_id][msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _id, _currentValues[i], _value);
}
}
//////////////////////////////// IERC1155BatchTransferExtended ////////////////////////////////////
function batchTransfer(address _to, uint256[] _ids, uint256[] _values) external {
uint256 _id;
uint256 _value;
for (uint256 i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, msg.sender, _to, _id, _value);
}
}
function safeBatchTransfer(address _to, uint256[] _ids, uint256[] _values, bytes _data) external {
//this.batchTransfer(_to, _ids, _values);
for (uint256 i = 0; i < _ids.length; ++i) {
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(msg.sender, _to, _ids[i], _values[i], _data));
}
uint256 _id;
uint256 _value;
for (i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, msg.sender, _to, _id, _value);
}
}
//////////////////////////////// IERC1155BatchTransferExtended ////////////////////////////////////
// Optional meta data view Functions
// consider multi-lingual support for name?
function name(uint256 _id) external view returns (string) {
return items[_id].name;
}
function symbol(uint256 _id) external view returns (string) {
return symbols[_id];
}
function decimals(uint256 _id) external view returns (uint8) {
return decimals[_id];
}
function totalSupply(uint256 _id) external view returns (uint256) {
return items[_id].totalSupply;
}
function uri(uint256 _id) external view returns (string) {
return metadataURIs[_id];
}
////////////////////////////////////////// OPTIONALS //////////////////////////////////////////////
function multicastTransfer(address[] _to, uint256[] _ids, uint256[] _values) external {
for (uint256 i = 0; i < _to.length; ++i) {
uint256 _id = _ids[i];
uint256 _value = _values[i];
address _dst = _to[i];
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_dst] = _value.add(items[_id].balances[_dst]);
Transfer(msg.sender, msg.sender, _dst, _id, _value);
}
}
function safeMulticastTransfer(address[] _to, uint256[] _ids, uint256[] _values, bytes _data) external {
//this.multicastTransfer(_to, _ids, _values);
for (uint256 i = 0; i < _ids.length; ++i) {
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(msg.sender, _to[i], _ids[i], _values[i], _data));
}
for (i = 0; i < _to.length; ++i) {
uint256 _id = _ids[i];
uint256 _value = _values[i];
address _dst = _to[i];
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_dst] = _value.add(items[_id].balances[_dst]);
Transfer(msg.sender, msg.sender, _dst, _id, _value);
}
}
////////////////////////////////////////// INTERNAL //////////////////////////////////////////////
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(
msg.sender, _from, _id, _value, _data);
return (retval == ERC1155_RECEIVED);
}
}
// File: contracts/ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// File: contracts/ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public;
}
// File: contracts/DepositContract.sol
/// @title DepositContract contract
contract DepositContract is withAccessManager {
bytes32 public clientId; // client ID.
uint256 public version = 2;
// EVENTS
event EtherTransfer(address to, uint256 value);
// NON-CONSTANT METHODS
/** @dev Constructor that sets the _clientID when the contract is deployed.
* @dev The method also sets the manager to the msg.sender.
* @param _clientId A string of fixed length representing the client ID.
*/
function DepositContract(bytes32 _clientId, address accessManager) public withAccessManager(accessManager) {
clientId = _clientId;
}
/** @dev Transfers an amount '_value' of tokens from msg.sender to '_to' address/wallet.
* @param populousTokenContract The address of the ERC20 token contract which implements the transfer method.
* @param _value the amount of tokens to transfer.
* @param _to The address/wallet to send to.
* @return success boolean true or false indicating whether the transfer was successful or not.
*/
function transfer(address populousTokenContract, address _to, uint256 _value) public
onlyServerOrOnlyPopulous returns (bool success)
{
return iERC20Token(populousTokenContract).transfer(_to, _value);
}
/** @dev This function will transfer iERC1155 tokens
*/
function transferERC1155(address _erc1155Token, address _to, uint256 _id, uint256 _value)
public onlyServerOrOnlyPopulous returns (bool success) {
ERC1155(_erc1155Token).safeTransfer(_to, _id, _value, "");
return true;
}
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer` if the recipient is a smart contract. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value (0x150b7a02) MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4) {
return 0x150b7a02;
}
/// @notice Handle the receipt of an ERC1155 type
/// @dev The smart contract calls this function on the recipient
/// after a `safeTransfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _id The identifier of the item being transferred
/// @param _value The amount of the item being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
/// unless throwing
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes _data) public returns(bytes4) {
return 0xf23a6e61;
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param erc721Token address of the erc721 token to target
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferERC721(
address erc721Token,
address _to,
uint256 _tokenId
)
public onlyServerOrOnlyPopulous returns (bool success)
{
// solium-disable-next-line arg-overflow
ERC721Basic(erc721Token).safeTransferFrom(this, _to, _tokenId, "");
return true;
}
/** @dev Transfers ether from this contract to a specified wallet/address
* @param _to An address implementing to send ether to.
* @param _value The amount of ether to send in wei.
* @return bool Successful or unsuccessful transfer
*/
function transferEther(address _to, uint256 _value) public
onlyServerOrOnlyPopulous returns (bool success)
{
require(this.balance >= _value);
require(_to.send(_value) == true);
EtherTransfer(_to, _value);
return true;
}
// payable function to allow this contract receive ether - for version 3
//function () public payable {}
// CONSTANT METHODS
/** @dev Returns the ether or token balance of the current contract instance using the ERC20 balanceOf method.
* @param populousTokenContract An address implementing the ERC20 token standard.
* @return uint An unsigned integer representing the returned token balance.
*/
function balanceOf(address populousTokenContract) public view returns (uint256) {
// ether
if (populousTokenContract == address(0)) {
return address(this).balance;
} else {
// erc20
return iERC20Token(populousTokenContract).balanceOf(this);
}
}
/**
* @dev Gets the balance of the specified address
* @param erc721Token address to erc721 token to target
* @return uint256 representing the amount owned by the passed address
*/
function balanceOfERC721(address erc721Token) public view returns (uint256) {
return ERC721Basic(erc721Token).balanceOf(this);
// returns ownedTokensCount[_owner];
}
/**
* @dev Gets the balance of the specified address
* @param _id the token id
* @param erc1155Token address to erc1155 token to target
* @return uint256 representing the amount owned by the passed address
*/
function balanceOfERC1155(address erc1155Token, uint256 _id) external view returns (uint256) {
return ERC1155(erc1155Token).balanceOf(_id, this);
}
/** @dev Gets the version of this deposit contract
* @return uint256 version
*/
function getVersion() public view returns (uint256) {
return version;
}
// CONSTANT FUNCTIONS
/** @dev This function gets the client ID or deposit contract owner
* returns _clientId
*/
function getClientId() public view returns (bytes32 _clientId) {
return clientId;
}
}
// File: contracts/SafeMath.sol
/// @title Overflow aware uint math functions.
/// @notice Inspired by https://github.com/MakerDAO/maker-otc/blob/master/contracts/simple_market.sol
library SafeMath {
/** @dev Safely multiplies two unsigned/non-negative integers.
* @dev Ensures that one of both numbers can be derived from dividing the product by the other.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
/** @dev Safely subtracts one number from another
* @dev Ensures that the number to subtract is lower.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/** @dev Safely adds two unsigned/non-negative integers.
* @dev Ensures that the sum of both numbers is greater or equal to one of both.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
// File: contracts/iDataManager.sol
/// @title DataManager contract
contract iDataManager {
// FIELDS
uint256 public version;
// currency symbol => currency erc20 contract address
mapping(bytes32 => address) public currencyAddresses;
// currency address => currency symbol
mapping(address => bytes32) public currencySymbols;
// clientId => depositAddress
mapping(bytes32 => address) public depositAddresses;
// depositAddress => clientId
mapping(address => bytes32) public depositClientIds;
// blockchainActionId => boolean
mapping(bytes32 => bool) public actionStatus;
// blockchainActionData
struct actionData {
bytes32 currency;
uint amount;
bytes32 accountId;
address to;
uint pptFee;
}
// blockchainActionId => actionData
mapping(bytes32 => actionData) public blockchainActionIdData;
//actionId => invoiceId
mapping(bytes32 => bytes32) public actionIdToInvoiceId;
// invoice provider company data
struct providerCompany {
//bool isEnabled;
bytes32 companyNumber;
bytes32 companyName;
bytes2 countryCode;
}
// companyCode => companyNumber => providerId
mapping(bytes2 => mapping(bytes32 => bytes32)) public providerData;
// providedId => providerCompany
mapping(bytes32 => providerCompany) public providerCompanyData;
// crowdsale invoiceDetails
struct _invoiceDetails {
bytes2 invoiceCountryCode;
bytes32 invoiceCompanyNumber;
bytes32 invoiceCompanyName;
bytes32 invoiceNumber;
}
// crowdsale invoiceData
struct invoiceData {
bytes32 providerUserId;
bytes32 invoiceCompanyName;
}
// country code => company number => invoice number => invoice data
mapping(bytes2 => mapping(bytes32 => mapping(bytes32 => invoiceData))) public invoices;
// NON-CONSTANT METHODS
/** @dev Adds a new deposit smart contract address linked to a client id
* @param _depositAddress the deposit smart contract address
* @param _clientId the client id
* @return success true/false denoting successful function call
*/
function setDepositAddress(bytes32 _blockchainActionId, address _depositAddress, bytes32 _clientId) public returns (bool success);
/** @dev Adds a new currency sumbol and smart contract address
* @param _currencyAddress the currency smart contract address
* @param _currencySymbol the currency symbol
* @return success true/false denoting successful function call
*/
function setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public returns (bool success);
/** @dev Updates a currency sumbol and smart contract address
* @param _currencyAddress the currency smart contract address
* @param _currencySymbol the currency symbol
* @return success true/false denoting successful function call
*/
function _setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public returns (bool success);
/** @dev set blockchain action data in struct
* @param _blockchainActionId the blockchain action id
* @param currency the token currency symbol
* @param accountId the clientId
* @param to the blockchain address or smart contract address used in the transaction
* @param amount the amount of tokens in the transaction
* @return success true/false denoting successful function call
*/
function setBlockchainActionData(
bytes32 _blockchainActionId, bytes32 currency,
uint amount, bytes32 accountId, address to, uint pptFee)
public
returns (bool success);
/** @dev upgrade deposit address
* @param _blockchainActionId the blockchain action id
* @param _clientId the client id
* @param _depositContract the deposit contract address for the client
* @return success true/false denoting successful function call
*/
function upgradeDepositAddress(bytes32 _blockchainActionId, bytes32 _clientId, address _depositContract) public returns (bool success);
/** @dev Updates a deposit address for client id
* @param _blockchainActionId the blockchain action id
* @param _clientId the client id
* @param _depositContract the deposit contract address for the client
* @return success true/false denoting successful function call
*/
function _setDepositAddress(bytes32 _blockchainActionId, bytes32 _clientId, address _depositContract) public returns (bool success);
/** @dev Add a new invoice to the platform
* @param _providerUserId the providers user id
* @param _invoiceCountryCode the country code of the provider
* @param _invoiceCompanyNumber the providers company number
* @param _invoiceCompanyName the providers company name
* @param _invoiceNumber the invoice number
* @return success true or false if function call is successful
*/
function setInvoice(
bytes32 _blockchainActionId, bytes32 _providerUserId, bytes2 _invoiceCountryCode,
bytes32 _invoiceCompanyNumber, bytes32 _invoiceCompanyName, bytes32 _invoiceNumber)
public returns (bool success);
/** @dev Add a new invoice provider to the platform
* @param _blockchainActionId the blockchain action id
* @param _userId the user id of the provider
* @param _companyNumber the providers company number
* @param _companyName the providers company name
* @param _countryCode the providers country code
* @return success true or false if function call is successful
*/
function setProvider(
bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber,
bytes32 _companyName, bytes2 _countryCode)
public returns (bool success);
/** @dev Update an added invoice provider to the platform
* @param _blockchainActionId the blockchain action id
* @param _userId the user id of the provider
* @param _companyNumber the providers company number
* @param _companyName the providers company name
* @param _countryCode the providers country code
* @return success true or false if function call is successful
*/
function _setProvider(
bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber,
bytes32 _companyName, bytes2 _countryCode)
public returns (bool success);
// CONSTANT METHODS
/** @dev Gets a deposit address with the client id
* @return clientDepositAddress The client's deposit address
*/
function getDepositAddress(bytes32 _clientId) public view returns (address clientDepositAddress);
/** @dev Gets a client id linked to a deposit address
* @return depositClientId The client id
*/
function getClientIdWithDepositAddress(address _depositContract) public view returns (bytes32 depositClientId);
/** @dev Gets a currency smart contract address
* @return currencyAddress The currency address
*/
function getCurrency(bytes32 _currencySymbol) public view returns (address currencyAddress);
/** @dev Gets a currency symbol given it's smart contract address
* @return currencySymbol The currency symbol
*/
function getCurrencySymbol(address _currencyAddress) public view returns (bytes32 currencySymbol);
/** @dev Gets details of a currency given it's smart contract address
* @return _symbol The currency symbol
* @return _name The currency name
* @return _decimals The currency decimal places/precision
*/
function getCurrencyDetails(address _currencyAddress) public view returns (bytes32 _symbol, bytes32 _name, uint8 _decimals);
/** @dev Get the blockchain action Id Data for a blockchain Action id
* @param _blockchainActionId the blockchain action id
* @return bytes32 currency
* @return uint amount
* @return bytes32 accountId
* @return address to
*/
function getBlockchainActionIdData(bytes32 _blockchainActionId) public view returns (bytes32 _currency, uint _amount, bytes32 _accountId, address _to);
/** @dev Get the bool status of a blockchain Action id
* @param _blockchainActionId the blockchain action id
* @return bool actionStatus
*/
function getActionStatus(bytes32 _blockchainActionId) public view returns (bool _blockchainActionStatus);
/** @dev Gets the details of an invoice with the country code, company number and invocie number.
* @param _invoiceCountryCode The country code.
* @param _invoiceCompanyNumber The company number.
* @param _invoiceNumber The invoice number
* @return providerUserId The invoice provider user Id
* @return invoiceCompanyName the invoice company name
*/
function getInvoice(bytes2 _invoiceCountryCode, bytes32 _invoiceCompanyNumber, bytes32 _invoiceNumber)
public
view
returns (bytes32 providerUserId, bytes32 invoiceCompanyName);
/** @dev Gets the details of an invoice provider with the country code and company number.
* @param _providerCountryCode The country code.
* @param _providerCompanyNumber The company number.
* @return isEnabled The boolean value true/false indicating whether invoice provider is enabled or not
* @return providerId The invoice provider user Id
* @return companyName the invoice company name
*/
function getProviderByCountryCodeCompanyNumber(bytes2 _providerCountryCode, bytes32 _providerCompanyNumber)
public
view
returns (bytes32 providerId, bytes32 companyName);
/** @dev Gets the details of an invoice provider with the providers user Id.
* @param _providerUserId The provider user Id.
* @return countryCode The invoice provider country code
* @return companyName the invoice company name
*/
function getProviderByUserId(bytes32 _providerUserId) public view
returns (bytes2 countryCode, bytes32 companyName, bytes32 companyNumber);
/** @dev Gets the version number for the current contract instance
* @return _version The version number
*/
function getVersion() public view returns (uint256 _version);
}
// File: contracts/DataManager.sol
/// @title DataManager contract
contract DataManager is iDataManager, withAccessManager {
// NON-CONSTANT METHODS
/** @dev Constructor that sets the server when contract is deployed.
* @param _accessManager The address to set as the access manager.
*/
function DataManager(address _accessManager, uint256 _version) public withAccessManager(_accessManager) {
version = _version;
}
/** @dev Adds a new deposit smart contract address linked to a client id
* @param _depositAddress the deposit smart contract address
* @param _clientId the client id
* @return success true/false denoting successful function call
*/
function setDepositAddress(bytes32 _blockchainActionId, address _depositAddress, bytes32 _clientId) public onlyServerOrOnlyPopulous returns (bool success) {
require(actionStatus[_blockchainActionId] == false);
require(depositAddresses[_clientId] == 0x0 && depositClientIds[_depositAddress] == 0x0);
depositAddresses[_clientId] = _depositAddress;
depositClientIds[_depositAddress] = _clientId;
assert(depositAddresses[_clientId] != 0x0 && depositClientIds[_depositAddress] != 0x0);
return true;
}
/** @dev Adds a new currency sumbol and smart contract address
* @param _currencyAddress the currency smart contract address
* @param _currencySymbol the currency symbol
* @return success true/false denoting successful function call
*/
function setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public onlyServerOrOnlyPopulous returns (bool success) {
require(actionStatus[_blockchainActionId] == false);
require(currencySymbols[_currencyAddress] == 0x0 && currencyAddresses[_currencySymbol] == 0x0);
currencySymbols[_currencyAddress] = _currencySymbol;
currencyAddresses[_currencySymbol] = _currencyAddress;
assert(currencyAddresses[_currencySymbol] != 0x0 && currencySymbols[_currencyAddress] != 0x0);
return true;
}
/** @dev Updates a currency sumbol and smart contract address
* @param _currencyAddress the currency smart contract address
* @param _currencySymbol the currency symbol
* @return success true/false denoting successful function call
*/
function _setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public onlyServerOrOnlyPopulous returns (bool success) {
require(actionStatus[_blockchainActionId] == false);
currencySymbols[_currencyAddress] = _currencySymbol;
currencyAddresses[_currencySymbol] = _currencyAddress;
assert(currencyAddresses[_currencySymbol] != 0x0 && currencySymbols[_currencyAddress] != 0x0);
setBlockchainActionData(_blockchainActionId, _currencySymbol, 0, 0x0, _currencyAddress, 0);
return true;
}
/** @dev set blockchain action data in struct
* @param _blockchainActionId the blockchain action id
* @param currency the token currency symbol
* @param accountId the clientId
* @param to the blockchain address or smart contract address used in the transaction
* @param amount the amount of tokens in the transaction
* @return success true/false denoting successful function call
*/
function setBlockchainActionData(
bytes32 _blockchainActionId, bytes32 currency,
uint amount, bytes32 accountId, address to, uint pptFee)
public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
blockchainActionIdData[_blockchainActionId].currency = currency;
blockchainActionIdData[_blockchainActionId].amount = amount;
blockchainActionIdData[_blockchainActionId].accountId = accountId;
blockchainActionIdData[_blockchainActionId].to = to;
blockchainActionIdData[_blockchainActionId].pptFee = pptFee;
actionStatus[_blockchainActionId] = true;
return true;
}
/** @dev Updates a deposit address for client id
* @param _blockchainActionId the blockchain action id
* @param _clientId the client id
* @param _depositContract the deposit contract address for the client
* @return success true/false denoting successful function call
*/
function _setDepositAddress(bytes32 _blockchainActionId, bytes32 _clientId, address _depositContract) public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
depositAddresses[_clientId] = _depositContract;
depositClientIds[_depositContract] = _clientId;
// check that deposit address has been stored for client Id
assert(depositAddresses[_clientId] == _depositContract && depositClientIds[_depositContract] == _clientId);
// set blockchain action data
setBlockchainActionData(_blockchainActionId, 0x0, 0, _clientId, depositAddresses[_clientId], 0);
return true;
}
/** @dev Add a new invoice to the platform
* @param _providerUserId the providers user id
* @param _invoiceCountryCode the country code of the provider
* @param _invoiceCompanyNumber the providers company number
* @param _invoiceCompanyName the providers company name
* @param _invoiceNumber the invoice number
* @return success true or false if function call is successful
*/
function setInvoice(
bytes32 _blockchainActionId, bytes32 _providerUserId, bytes2 _invoiceCountryCode,
bytes32 _invoiceCompanyNumber, bytes32 _invoiceCompanyName, bytes32 _invoiceNumber)
public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
bytes32 providerUserId;
bytes32 companyName;
(providerUserId, companyName) = getInvoice(_invoiceCountryCode, _invoiceCompanyNumber, _invoiceNumber);
require(providerUserId == 0x0 && companyName == 0x0);
// country code => company number => invoice number => invoice data
invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId = _providerUserId;
invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName = _invoiceCompanyName;
assert(
invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId != 0x0 &&
invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName != 0x0
);
return true;
}
/** @dev Add a new invoice provider to the platform
* @param _blockchainActionId the blockchain action id
* @param _userId the user id of the provider
* @param _companyNumber the providers company number
* @param _companyName the providers company name
* @param _countryCode the providers country code
* @return success true or false if function call is successful
*/
function setProvider(
bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber,
bytes32 _companyName, bytes2 _countryCode)
public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
require(
providerCompanyData[_userId].companyNumber == 0x0 &&
providerCompanyData[_userId].countryCode == 0x0 &&
providerCompanyData[_userId].companyName == 0x0);
providerCompanyData[_userId].countryCode = _countryCode;
providerCompanyData[_userId].companyName = _companyName;
providerCompanyData[_userId].companyNumber = _companyNumber;
providerData[_countryCode][_companyNumber] = _userId;
return true;
}
/** @dev Update an added invoice provider to the platform
* @param _blockchainActionId the blockchain action id
* @param _userId the user id of the provider
* @param _companyNumber the providers company number
* @param _companyName the providers company name
* @param _countryCode the providers country code
* @return success true or false if function call is successful
*/
function _setProvider(
bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber,
bytes32 _companyName, bytes2 _countryCode)
public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
providerCompanyData[_userId].countryCode = _countryCode;
providerCompanyData[_userId].companyName = _companyName;
providerCompanyData[_userId].companyNumber = _companyNumber;
providerData[_countryCode][_companyNumber] = _userId;
setBlockchainActionData(_blockchainActionId, 0x0, 0, _userId, 0x0, 0);
return true;
}
// CONSTANT METHODS
/** @dev Gets a deposit address with the client id
* @return clientDepositAddress The client's deposit address
*/
function getDepositAddress(bytes32 _clientId) public view returns (address clientDepositAddress){
return depositAddresses[_clientId];
}
/** @dev Gets a client id linked to a deposit address
* @return depositClientId The client id
*/
function getClientIdWithDepositAddress(address _depositContract) public view returns (bytes32 depositClientId){
return depositClientIds[_depositContract];
}
/** @dev Gets a currency smart contract address
* @return currencyAddress The currency address
*/
function getCurrency(bytes32 _currencySymbol) public view returns (address currencyAddress) {
return currencyAddresses[_currencySymbol];
}
/** @dev Gets a currency symbol given it's smart contract address
* @return currencySymbol The currency symbol
*/
function getCurrencySymbol(address _currencyAddress) public view returns (bytes32 currencySymbol) {
return currencySymbols[_currencyAddress];
}
/** @dev Gets details of a currency given it's smart contract address
* @return _symbol The currency symbol
* @return _name The currency name
* @return _decimals The currency decimal places/precision
*/
function getCurrencyDetails(address _currencyAddress) public view returns (bytes32 _symbol, bytes32 _name, uint8 _decimals) {
return (CurrencyToken(_currencyAddress).symbol(), CurrencyToken(_currencyAddress).name(), CurrencyToken(_currencyAddress).decimals());
}
/** @dev Get the blockchain action Id Data for a blockchain Action id
* @param _blockchainActionId the blockchain action id
* @return bytes32 currency
* @return uint amount
* @return bytes32 accountId
* @return address to
*/
function getBlockchainActionIdData(bytes32 _blockchainActionId) public view
returns (bytes32 _currency, uint _amount, bytes32 _accountId, address _to)
{
require(actionStatus[_blockchainActionId] == true);
return (blockchainActionIdData[_blockchainActionId].currency,
blockchainActionIdData[_blockchainActionId].amount,
blockchainActionIdData[_blockchainActionId].accountId,
blockchainActionIdData[_blockchainActionId].to);
}
/** @dev Get the bool status of a blockchain Action id
* @param _blockchainActionId the blockchain action id
* @return bool actionStatus
*/
function getActionStatus(bytes32 _blockchainActionId) public view returns (bool _blockchainActionStatus) {
return actionStatus[_blockchainActionId];
}
/** @dev Gets the details of an invoice with the country code, company number and invocie number.
* @param _invoiceCountryCode The country code.
* @param _invoiceCompanyNumber The company number.
* @param _invoiceNumber The invoice number
* @return providerUserId The invoice provider user Id
* @return invoiceCompanyName the invoice company name
*/
function getInvoice(bytes2 _invoiceCountryCode, bytes32 _invoiceCompanyNumber, bytes32 _invoiceNumber)
public
view
returns (bytes32 providerUserId, bytes32 invoiceCompanyName)
{
bytes32 _providerUserId = invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId;
bytes32 _invoiceCompanyName = invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName;
return (_providerUserId, _invoiceCompanyName);
}
/** @dev Gets the details of an invoice provider with the country code and company number.
* @param _providerCountryCode The country code.
* @param _providerCompanyNumber The company number.
* @return isEnabled The boolean value true/false indicating whether invoice provider is enabled or not
* @return providerId The invoice provider user Id
* @return companyName the invoice company name
*/
function getProviderByCountryCodeCompanyNumber(bytes2 _providerCountryCode, bytes32 _providerCompanyNumber)
public
view
returns (bytes32 providerId, bytes32 companyName)
{
bytes32 providerUserId = providerData[_providerCountryCode][_providerCompanyNumber];
return (providerUserId,
providerCompanyData[providerUserId].companyName);
}
/** @dev Gets the details of an invoice provider with the providers user Id.
* @param _providerUserId The provider user Id.
* @return countryCode The invoice provider country code
* @return companyName the invoice company name
*/
function getProviderByUserId(bytes32 _providerUserId) public view
returns (bytes2 countryCode, bytes32 companyName, bytes32 companyNumber)
{
return (providerCompanyData[_providerUserId].countryCode,
providerCompanyData[_providerUserId].companyName,
providerCompanyData[_providerUserId].companyNumber);
}
/** @dev Gets the version number for the current contract instance
* @return _version The version number
*/
function getVersion() public view returns (uint256 _version) {
return version;
}
}
// File: contracts/Populous.sol
/**
This is the core module of the system. Currently it holds the code of
the Bank and crowdsale modules to avoid external calls and higher gas costs.
It might be a good idea in the future to split the code, separate Bank
and crowdsale modules into external files and have the core interact with them
with addresses and interfaces.
*/
/// @title Populous contract
contract Populous is withAccessManager {
// EVENTS
// Bank events
event EventUSDCToUSDp(bytes32 _blockchainActionId, bytes32 _clientId, uint amount);
event EventUSDpToUSDC(bytes32 _blockchainActionId, bytes32 _clientId, uint amount);
event EventDepositAddressUpgrade(bytes32 blockchainActionId, address oldDepositContract, address newDepositContract, bytes32 clientId, uint256 version);
event EventWithdrawPPT(bytes32 blockchainActionId, bytes32 accountId, address depositContract, address to, uint amount);
event EventWithdrawPoken(bytes32 _blockchainActionId, bytes32 accountId, bytes32 currency, uint amount);
event EventNewDepositContract(bytes32 blockchainActionId, bytes32 clientId, address depositContractAddress, uint256 version);
event EventWithdrawXAUp(bytes32 _blockchainActionId, address erc1155Token, uint amount, uint token_id, bytes32 accountId, uint pptFee);
// FIELDS
struct tokens {
address _token;
uint256 _precision;
}
mapping(bytes8 => tokens) public tokenDetails;
// NON-CONSTANT METHODS
// Constructor method called when contract instance is
// deployed with 'withAccessManager' modifier.
function Populous(address _accessManager) public withAccessManager(_accessManager) {
/*ropsten
//pxt
tokenDetails[0x505854]._token = 0xD8A7C588f8DC19f49dAFd8ecf08eec58e64d4cC9;
tokenDetails[0x505854]._precision = 8;
//usdc
tokenDetails[0x55534443]._token = 0xF930f2C7Bc02F89D05468112520553FFc6D24801;
tokenDetails[0x55534443]._precision = 6;
//tusd
tokenDetails[0x54555344]._token = 0x78e7BEE398D66660bDF820DbDB415A33d011cD48;
tokenDetails[0x54555344]._precision = 18;
//ppt
tokenDetails[0x505054]._token = 0x0ff72e24AF7c09A647865820D4477F98fcB72a2c;
tokenDetails[0x505054]._precision = 8;
//xau
tokenDetails[0x584155]._token = 0x9b935E3779098bC5E1ffc073CaF916F1E92A6145;
tokenDetails[0x584155]._precision = 0;
//usdp
tokenDetails[0x55534470]._token = 0xf4b1533b6F45fAC936fA508F7e5db6d4BbC4c8bd;
tokenDetails[0x55534470]._precision = 6;
*/
/*livenet*/
//pxt
tokenDetails[0x505854]._token = 0xc14830E53aA344E8c14603A91229A0b925b0B262;
tokenDetails[0x505854]._precision = 8;
//usdc
tokenDetails[0x55534443]._token = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
tokenDetails[0x55534443]._precision = 6;
//tusd
tokenDetails[0x54555344]._token = 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E;
tokenDetails[0x54555344]._precision = 18;
//ppt
tokenDetails[0x505054]._token = 0xd4fa1460F537bb9085d22C7bcCB5DD450Ef28e3a;
tokenDetails[0x505054]._precision = 8;
//xau
tokenDetails[0x584155]._token = 0x73a3b7DFFE9af119621f8467D8609771AB4BC33f;
tokenDetails[0x584155]._precision = 0;
//usdp
tokenDetails[0x55534470]._token = 0xBaB5D0f110Be6f4a5b70a2FA22eD17324bFF6576;
tokenDetails[0x55534470]._precision = 6;
}
/**
BANK MODULE
*/
// NON-CONSTANT METHODS
function usdcToUsdp(
address _dataManager, bytes32 _blockchainActionId,
bytes32 _clientId, uint amount)
public
onlyServer
{
// client deposit smart contract address
address _depositAddress = DataManager(_dataManager).getDepositAddress(_clientId);
require(_dataManager != 0x0 && _depositAddress != 0x0 && amount > 0);
//transfer usdc from deposit contract to server/admin
require(DepositContract(_depositAddress).transfer(tokenDetails[0x55534443]._token, msg.sender, amount) == true);
// mint USDp into depositAddress with amount
require(CurrencyToken(tokenDetails[0x55534470]._token).mint(amount, _depositAddress) == true);
//set action data
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x55534470, amount, _clientId, _depositAddress, 0) == true);
//event
emit EventUSDCToUSDp(_blockchainActionId, _clientId, amount);
}
function usdpToUsdc(
address _dataManager, bytes32 _blockchainActionId,
bytes32 _clientId, uint amount)
public
onlyServer
{
// client deposit smart contract address
address _depositAddress = DataManager(_dataManager).getDepositAddress(_clientId);
require(_dataManager != 0x0 && _depositAddress != 0x0 && amount > 0);
//destroyFrom depositAddress USDp amount
require(CurrencyToken(tokenDetails[0x55534470]._token).destroyTokensFrom(amount, _depositAddress) == true);
//transferFrom USDC from server to depositAddress
require(CurrencyToken(tokenDetails[0x55534443]._token).transferFrom(msg.sender, _depositAddress, amount) == true);
//set action data
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x55534470, amount, _clientId, _depositAddress, 0) == true);
//event
emit EventUSDpToUSDC(_blockchainActionId, _clientId, amount);
}
// Creates a new 'depositAddress' gotten from deploying a deposit contract linked to a client ID
function createAddress(address _dataManager, bytes32 _blockchainActionId, bytes32 clientId)
public
onlyServer
{
require(_dataManager != 0x0);
DepositContract newDepositContract;
DepositContract dc;
if (DataManager(_dataManager).getDepositAddress(clientId) != 0x0) {
dc = DepositContract(DataManager(_dataManager).getDepositAddress(clientId));
newDepositContract = new DepositContract(clientId, AM);
require(!dc.call(bytes4(keccak256("getVersion()"))));
// only checking version 1 now to upgrade to version 2
address PXT = tokenDetails[0x505854]._token;
address PPT = tokenDetails[0x505054]._token;
if(dc.balanceOf(PXT) > 0){
require(dc.transfer(PXT, newDepositContract, dc.balanceOf(PXT)) == true);
}
if(dc.balanceOf(PPT) > 0) {
require(dc.transfer(PPT, newDepositContract, dc.balanceOf(PPT)) == true);
}
require(DataManager(_dataManager)._setDepositAddress(_blockchainActionId, clientId, newDepositContract) == true);
EventDepositAddressUpgrade(_blockchainActionId, address(dc), DataManager(_dataManager).getDepositAddress(clientId), clientId, newDepositContract.getVersion());
} else {
newDepositContract = new DepositContract(clientId, AM);
require(DataManager(_dataManager).setDepositAddress(_blockchainActionId, newDepositContract, clientId) == true);
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x0, 0, clientId, DataManager(_dataManager).getDepositAddress(clientId), 0) == true);
EventNewDepositContract(_blockchainActionId, clientId, DataManager(_dataManager).getDepositAddress(clientId), newDepositContract.getVersion());
}
}
/* /// Ether to XAUp exchange between deposit contract and Populous.sol
function exchangeXAUP(
address _dataManager, bytes32 _blockchainActionId,
address erc20_tokenAddress, uint erc20_amount, uint xaup_amount,
uint _tokenId, bytes32 _clientId, address adminExternalWallet)
public
onlyServer
{
ERC1155 xa = ERC1155(tokenDetails[0x584155]._token);
// client deposit smart contract address
address _depositAddress = DataManager(_dataManager).getDepositAddress(_clientId);
require(
// check dataManager contract is valid
_dataManager != 0x0 &&
// check deposit address of client
_depositAddress != 0x0 &&
// check xaup token address
// tokenDetails[0x584155]._token != 0x0 &&
erc20_tokenAddress != 0x0 &&
// check action id is unused
DataManager(_dataManager).getActionStatus(_blockchainActionId) == false &&
// deposit contract version >= 2
DepositContract(_depositAddress).getVersion() >= 2 &&
// populous server xaup balance
xa.balanceOf(_tokenId, msg.sender) >= xaup_amount
);
// transfer erc20 token balance from clients deposit contract to server/admin
require(DepositContract(_depositAddress).transfer(erc20_tokenAddress, adminExternalWallet, erc20_amount) == true);
// transfer xaup tokens to clients deposit address from populous server allowance
xa.safeTransferFrom(msg.sender, _depositAddress, _tokenId, xaup_amount, "");
// set action status in dataManager
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x0, erc20_amount, _clientId, _depositAddress, 0) == true);
// emit event
EventExchangeXAUp(_blockchainActionId, erc20_tokenAddress, erc20_amount, xaup_amount, _tokenId, _clientId, _depositAddress);
} */
/** dev Import an amount of pokens of a particular currency from an ethereum wallet/address to bank
* @param _blockchainActionId the blockchain action id
* @param accountId the account id of the client
* @param from the blockchain address to import pokens from
* @param currency the poken currency
*/
function withdrawPoken(
address _dataManager, bytes32 _blockchainActionId,
bytes32 currency, uint256 amount, uint256 amountUSD,
address from, address to, bytes32 accountId,
uint256 inCollateral,
uint256 pptFee, address adminExternalWallet)
public
onlyServer
{
require(_dataManager != 0x0);
//DataManager dm = DataManager(_dataManager);
require(DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && DataManager(_dataManager).getDepositAddress(accountId) != 0x0);
require(adminExternalWallet != 0x0 && pptFee > 0 && amount > 0);
require(DataManager(_dataManager).getCurrency(currency) != 0x0);
DepositContract o = DepositContract(DataManager(_dataManager).getDepositAddress(accountId));
// check if pptbalance minus collateral held is more than pptFee then transfer pptFee from users ppt deposit to adminWallet
require(SafeMath.safeSub(o.balanceOf(tokenDetails[0x505054]._token), inCollateral) >= pptFee);
require(o.transfer(tokenDetails[0x505054]._token, adminExternalWallet, pptFee) == true);
// WITHDRAW PART / DEBIT
if(amount > CurrencyToken(DataManager(_dataManager).getCurrency(currency)).balanceOf(from)) {
// destroying total balance as user has less than pokens they want to withdraw
require(CurrencyToken(DataManager(_dataManager).getCurrency(currency)).destroyTokensFrom(CurrencyToken(DataManager(_dataManager).getCurrency(currency)).balanceOf(from), from) == true);
//remaining ledger balance of deposit address is 0
} else {
// destroy amount from balance as user has more than pokens they want to withdraw
require(CurrencyToken(DataManager(_dataManager).getCurrency(currency)).destroyTokensFrom(amount, from) == true);
//left over balance is deposit address balance.
}
// TRANSFER PART / CREDIT
// approve currency amount for populous for the next require to pass
if(amountUSD > 0) //give the user USDC
{
CurrencyToken(tokenDetails[0x55534443]._token).transferFrom(msg.sender, to, amountUSD);
}else { //give the user GBP / poken currency
CurrencyToken(DataManager(_dataManager).getCurrency(currency)).transferFrom(msg.sender, to, amount);
}
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, currency, amount, accountId, to, pptFee) == true);
EventWithdrawPoken(_blockchainActionId, accountId, currency, amount);
}
/** @dev Withdraw an amount of PPT Populous tokens to a blockchain address
* @param _blockchainActionId the blockchain action id
* @param pptAddress the address of the PPT smart contract
* @param accountId the account id of the client
* @param pptFee the amount of fees to pay in PPT tokens
* @param adminExternalWallet the platform admin wallet address to pay the fees to
* @param to the blockchain address to withdraw and transfer the pokens to
* @param inCollateral the amount of pokens withheld by the platform
*/
function withdrawERC20(
address _dataManager, bytes32 _blockchainActionId,
address pptAddress, bytes32 accountId,
address to, uint256 amount, uint256 inCollateral,
uint256 pptFee, address adminExternalWallet)
public
onlyServer
{
require(_dataManager != 0x0);
require(DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && DataManager(_dataManager).getDepositAddress(accountId) != 0x0);
require(adminExternalWallet != 0x0 && pptFee >= 0 && amount > 0);
address depositContract = DataManager(_dataManager).getDepositAddress(accountId);
if(pptAddress == tokenDetails[0x505054]._token) {
uint pptBalance = SafeMath.safeSub(DepositContract(depositContract).balanceOf(tokenDetails[0x505054]._token), inCollateral);
require(pptBalance >= SafeMath.safeAdd(amount, pptFee));
} else {
uint erc20Balance = DepositContract(depositContract).balanceOf(pptAddress);
require(erc20Balance >= amount);
}
require(DepositContract(depositContract).transfer(tokenDetails[0x505054]._token, adminExternalWallet, pptFee) == true);
require(DepositContract(depositContract).transfer(pptAddress, to, amount) == true);
bytes32 tokenSymbol = iERC20Token(pptAddress).symbol();
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, tokenSymbol, amount, accountId, to, pptFee) == true);
EventWithdrawPPT(_blockchainActionId, accountId, DataManager(_dataManager).getDepositAddress(accountId), to, amount);
}
// erc1155 withdraw function from deposit contract
/* function withdrawERC1155(
address _dataManager, bytes32 _blockchainActionId,
address _to, uint256 _id, uint256 _value,
bytes32 accountId, uint256 pptFee,
address adminExternalWallet)
public
onlyServer
{
require(DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && DataManager(_dataManager).getDepositAddress(accountId) != 0x0);
require(adminExternalWallet != 0x0 && pptFee > 0 && _value > 0);
DepositContract o = DepositContract(DataManager(_dataManager).getDepositAddress(accountId));
require(o.transfer(tokenDetails[0x505054]._token, adminExternalWallet, pptFee) == true);
// transfer xaup tokens to address from deposit contract
require(o.transferERC1155(tokenDetails[0x584155]._token, _to, _id, _value) == true);
// set action status in dataManager
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x584155, _value, accountId, _to, pptFee) == true);
// emit event
EventWithdrawXAUp(_blockchainActionId, tokenDetails[0x584155]._token, _value, _id, accountId, pptFee);
} */
} | this.batchTransfer(_to, _ids, _values); solium-disable-next-line arg-overflow | function safeBatchTransfer(address _to, uint256[] _ids, uint256[] _values, bytes _data) external {
for (uint256 i = 0; i < _ids.length; ++i) {
require(_checkAndCallSafeTransfer(msg.sender, _to, _ids[i], _values[i], _data));
}
uint256 _id;
uint256 _value;
for (i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, msg.sender, _to, _id, _value);
}
}
| 5,475,775 |
./partial_match/3/0x3bF4788621B18eCE94B9C2F916b39FDB6d1dF8aa/sources/MineDAPP.sol | change baseMiningRate | function x_adminChangeBaseRate(uint256 _amount) external onlyOwner returns(bool) {
baseMiningRate = _amount;
return true;
}
| 5,272,054 |
./full_match/80001/0x8B89359a48C153994d2A6BF878b148f151d2A0c4/sources/contracts/market/MarketMatching.sol | Cancel an offer. Refunds offer maker. | function cancel(uint256 id) public can_cancel(id) returns (bool success) {
require(!_locked, _S102);
require(_unsort(id), _T110);
}
| 9,473,640 |
pragma solidity ^0.4.13;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function getOwner() returns(address){
return owner;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
* Базовый контракт, который поддерживает остановку продаж
*/
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require(!halted);
_;
}
/* Модификатор, который вызывается в потомках */
modifier onlyInEmergency {
require(halted);
_;
}
/* Вызов функции прервет продажи, вызывать может только владелец */
function halt() external onlyOwner {
halted = true;
}
/* Вызов возвращает режим продаж */
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
/**
* Различные валидаторы
*/
contract ValidationUtil {
function requireNotEmptyAddress(address value) internal{
require(isAddressValid(value));
}
function isAddressValid(address value) internal constant returns (bool result){
return value != 0;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* Шаблон для токена, который можно сжечь
*/
contract BurnableToken is StandardToken, Ownable, ValidationUtil {
using SafeMath for uint;
address public tokenOwnerBurner;
/** Событие, сколько токенов мы сожгли */
event Burned(address burner, uint burnedAmount);
function setOwnerBurner(address _tokenOwnerBurner) public onlyOwner invalidOwnerBurner{
// Проверка, что адрес не пустой
requireNotEmptyAddress(_tokenOwnerBurner);
tokenOwnerBurner = _tokenOwnerBurner;
}
/**
* Сжигаем токены на балансе владельца токенов, вызвать может только tokenOwnerBurner
*/
function burnOwnerTokens(uint burnAmount) public onlyTokenOwnerBurner validOwnerBurner{
burnTokens(tokenOwnerBurner, burnAmount);
}
/**
* Сжигаем токены на балансе адреса токенов, вызвать может только tokenOwnerBurner
*/
function burnTokens(address _address, uint burnAmount) public onlyTokenOwnerBurner validOwnerBurner{
balances[_address] = balances[_address].sub(burnAmount);
// Вызываем событие
Burned(_address, burnAmount);
}
/**
* Сжигаем все токены на балансе владельца
*/
function burnAllOwnerTokens() public onlyTokenOwnerBurner validOwnerBurner{
uint burnAmount = balances[tokenOwnerBurner];
burnTokens(tokenOwnerBurner, burnAmount);
}
/** Модификаторы
*/
modifier onlyTokenOwnerBurner() {
require(msg.sender == tokenOwnerBurner);
_;
}
modifier validOwnerBurner() {
// Проверка, что адрес не пустой
requireNotEmptyAddress(tokenOwnerBurner);
_;
}
modifier invalidOwnerBurner() {
// Проверка, что адрес не пустой
require(!isAddressValid(tokenOwnerBurner));
_;
}
}
/**
* Токен продаж
*
* ERC-20 токен, для ICO
*
*/
contract CrowdsaleToken is StandardToken, Ownable {
/* Описание см. в конструкторе */
string public name;
string public symbol;
uint public decimals;
address public mintAgent;
/** Событие обновления токена (имя и символ) */
event UpdatedTokenInformation(string newName, string newSymbol);
/** Событие выпуска токенов */
event TokenMinted(uint amount, address toAddress);
/**
* Конструктор
*
* Токен должен быть создан только владельцем через кошелек (либо с мультиподписью, либо без нее)
*
* @param _name - имя токена
* @param _symbol - символ токена
* @param _decimals - кол-во знаков после запятой
*/
function CrowdsaleToken(string _name, string _symbol, uint _decimals) {
owner = msg.sender;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
* Владелец должен вызвать эту функцию, чтобы выпустить токены на адрес
*/
function mintToAddress(uint amount, address toAddress) onlyMintAgent{
// перевод токенов на аккаунт
balances[toAddress] = amount;
// вызываем событие
TokenMinted(amount, toAddress);
}
/**
* Владелец может обновить инфу по токену
*/
function setTokenInformation(string _name, string _symbol) onlyOwner {
name = _name;
symbol = _symbol;
// Вызываем событие
UpdatedTokenInformation(name, symbol);
}
/**
* Только владелец может обновить агента для создания токенов
*/
function setMintAgent(address _address) onlyOwner {
mintAgent = _address;
}
modifier onlyMintAgent(){
require(msg.sender == mintAgent);
_;
}
}
/**
* Шаблон для продаж токена, который можно сжечь
*
*/
contract BurnableCrowdsaleToken is BurnableToken, CrowdsaleToken {
function BurnableCrowdsaleToken(string _name, string _symbol, uint _decimals) CrowdsaleToken(_name, _symbol, _decimals) BurnableToken(){
}
}
/**
* Базовый контракт для продаж
*
* Содержит
* - Дата начала и конца
*/
/* Продажи могут быть остановлены в любой момент по вызову halt() */
contract AllocatedCappedCrowdsale is Haltable, ValidationUtil {
using SafeMath for uint;
// Кол-во токенов для распределения
uint public advisorsTokenAmount = 8040817;
uint public supportTokenAmount = 3446064;
uint public marketingTokenAmount = 3446064;
uint public teamTokenAmount = 45947521;
uint public teamTokensIssueDate;
/* Токен, который продаем */
BurnableCrowdsaleToken public token;
/* Адрес, куда будут переведена собранная сумма, в случае успеха */
address public destinationMultisigWallet;
/* Первая стадия в формате UNIX timestamp */
uint public firstStageStartsAt;
/* Конец продаж в формате UNIX timestamp */
uint public firstStageEndsAt;
/* Вторая стадия в формате UNIX timestamp */
uint public secondStageStartsAt;
/* Конец продаж в формате UNIX timestamp */
uint public secondStageEndsAt;
/* Минимальная кепка для первой стадии в центах */
uint public softCapFundingGoalInCents = 392000000;
/* Минимальная кепка для второй стадии в центах */
uint public hardCapFundingGoalInCents = 985000000;
/* Сколько всего в wei мы получили 10^18 wei = 1 ether */
uint public weiRaised;
/* Сколько всего собрали в ценах на первой стадии */
uint public firstStageRaisedInWei;
/* Сколько всего собрали в ценах на второй стадии */
uint public secondStageRaisedInWei;
/* Кол-во уникальных адресов, которые у наc получили токены */
uint public investorCount;
/* Сколько wei отдали инвесторам на refund'е в wei */
uint public weiRefunded;
/* Сколько токенов продали всего */
uint public tokensSold;
/* Флаг того, что сработал финализатор первой стадии */
bool public isFirstStageFinalized;
/* Флаг того, что сработал финализатор второй стадии */
bool public isSecondStageFinalized;
/* Флаг нормального завершнения продаж */
bool public isSuccessOver;
/* Флаг того, что начался процесс возврата */
bool public isRefundingEnabled;
/* Сколько сейчас стоит 1 eth в центах, округленная до целых */
uint public currentEtherRateInCents;
/* Текущая стоимость токена в центах */
uint public oneTokenInCents = 7;
/* Выпущены ли токены для первой стадии */
bool public isFirstStageTokensMinted;
/* Выпущены ли токены для второй стадии */
bool public isSecondStageTokensMinted;
/* Кол-во токенов для первой стадии */
uint public firstStageTotalSupply = 112000000;
/* Кол-во токенов проданных на первой стадии*/
uint public firstStageTokensSold;
/* Кол-во токенов для второй стадии */
uint public secondStageTotalSupply = 229737610;
/* Кол-во токенов проданных на второй стадии*/
uint public secondStageTokensSold;
/* Кол-во токенов, которые находятся в резерве и не продаются, после успеха, они распределяются в соотвествии с Token Policy на второй стадии*/
uint public secondStageReserve = 60880466;
/* Кол-во токенов предназначенных для продажи, на второй стадии*/
uint public secondStageTokensForSale;
/* Мапа адрес инвестора - кол-во выданных токенов */
mapping (address => uint) public tokenAmountOf;
/* Мапа, адрес инвестора - кол-во эфира */
mapping (address => uint) public investedAmountOf;
/* Адреса, куда будут распределены токены */
address public advisorsAccount;
address public marketingAccount;
address public supportAccount;
address public teamAccount;
/** Возможные состояния
*
* - Prefunding: подготовка, залили контракт, но текущая дата меньше даты первой стадии
* - FirstStageFunding: Продажи первой стадии
* - FirstStageEnd: Окончены продажи первой стадии, но еще не вызван финализатор первой стадии
* - SecondStageFunding: Продажи второго этапа
* - SecondStageEnd: Окончены продажи второй стадии, но не вызван финализатор второй сдадии
* - Success: Успешно закрыли ICO
* - Failure: Не собрали Soft Cap
* - Refunding: Возвращаем собранный эфир
*/
enum State{PreFunding, FirstStageFunding, FirstStageEnd, SecondStageFunding, SecondStageEnd, Success, Failure, Refunding}
// Событие покупки токена
event Invested(address indexed investor, uint weiAmount, uint tokenAmount, uint centAmount, uint txId);
// Событие изменения курса eth
event ExchangeRateChanged(uint oldExchangeRate, uint newExchangeRate);
// Событие изменения даты окончания первой стадии
event FirstStageStartsAtChanged(uint newFirstStageStartsAt);
event FirstStageEndsAtChanged(uint newFirstStageEndsAt);
// Событие изменения даты окончания второй стадии
event SecondStageStartsAtChanged(uint newSecondStageStartsAt);
event SecondStageEndsAtChanged(uint newSecondStageEndsAt);
// Событие изменения Soft Cap'а
event SoftCapChanged(uint newGoal);
// Событие изменения Hard Cap'а
event HardCapChanged(uint newGoal);
// Конструктор
function AllocatedCappedCrowdsale(uint _currentEtherRateInCents, address _token, address _destinationMultisigWallet, uint _firstStageStartsAt, uint _firstStageEndsAt, uint _secondStageStartsAt, uint _secondStageEndsAt, address _advisorsAccount, address _marketingAccount, address _supportAccount, address _teamAccount, uint _teamTokensIssueDate) {
requireNotEmptyAddress(_destinationMultisigWallet);
// Проверка, что даты установлены
require(_firstStageStartsAt != 0);
require(_firstStageEndsAt != 0);
require(_firstStageStartsAt < _firstStageEndsAt);
require(_secondStageStartsAt != 0);
require(_secondStageEndsAt != 0);
require(_secondStageStartsAt < _secondStageEndsAt);
require(_teamTokensIssueDate != 0);
// Токен, который поддерживает сжигание
token = BurnableCrowdsaleToken(_token);
destinationMultisigWallet = _destinationMultisigWallet;
firstStageStartsAt = _firstStageStartsAt;
firstStageEndsAt = _firstStageEndsAt;
secondStageStartsAt = _secondStageStartsAt;
secondStageEndsAt = _secondStageEndsAt;
// Адреса кошельков для адвизоров, маркетинга, команды
advisorsAccount = _advisorsAccount;
marketingAccount = _marketingAccount;
supportAccount = _supportAccount;
teamAccount = _teamAccount;
teamTokensIssueDate = _teamTokensIssueDate;
currentEtherRateInCents = _currentEtherRateInCents;
secondStageTokensForSale = secondStageTotalSupply.sub(secondStageReserve);
}
/**
* Функция, инициирующая нужное кол-во токенов для первого этапа продаж, вызвать можно только 1 раз
*/
function mintTokensForFirstStage() public onlyOwner {
// Если уже создали токены для первой стадии, делаем откат
require(!isFirstStageTokensMinted);
uint tokenMultiplier = 10 ** token.decimals();
token.mintToAddress(firstStageTotalSupply.mul(tokenMultiplier), address(this));
isFirstStageTokensMinted = true;
}
/**
* Функция, инициирующая нужное кол-во токенов для второго этапа продаж, только в случае, если это еще не сделано и были созданы токены для первой стадии
*/
function mintTokensForSecondStage() private {
// Если уже создали токены для второй стадии, делаем откат
require(!isSecondStageTokensMinted);
require(isFirstStageTokensMinted);
uint tokenMultiplier = 10 ** token.decimals();
token.mintToAddress(secondStageTotalSupply.mul(tokenMultiplier), address(this));
isSecondStageTokensMinted = true;
}
/**
* Функция возвращающая текущую стоимость 1 токена в wei
*/
function getOneTokenInWei() external constant returns(uint){
return oneTokenInCents.mul(10 ** 18).div(currentEtherRateInCents);
}
/**
* Функция, которая переводит wei в центы по текущему курсу
*/
function getWeiInCents(uint value) public constant returns(uint){
return currentEtherRateInCents.mul(value).div(10 ** 18);
}
/**
* Перевод токенов покупателю
*/
function assignTokens(address receiver, uint tokenAmount) private {
// Если перевод не удался, откатываем транзакцию
if (!token.transfer(receiver, tokenAmount)) revert();
}
/**
* Fallback функция вызывающаяся при переводе эфира
*/
function() payable {
buy();
}
/**
* Низкоуровневая функция перевода эфира и выдачи токенов
*/
function internalAssignTokens(address receiver, uint tokenAmount, uint weiAmount, uint centAmount, uint txId) internal {
// Переводим токены инвестору
assignTokens(receiver, tokenAmount);
// Вызываем событие
Invested(receiver, weiAmount, tokenAmount, centAmount, txId);
// Может переопределяеться в наследниках
}
/**
* Инвестиции
* Должен быть включен режим продаж первой или второй стадии и не собран Hard Cap
* @param receiver - эфирный адрес получателя
* @param txId - id внешней транзакции
*/
function internalInvest(address receiver, uint weiAmount, uint txId) stopInEmergency inFirstOrSecondFundingState notHardCapReached internal {
State currentState = getState();
uint tokenMultiplier = 10 ** token.decimals();
uint amountInCents = getWeiInCents(weiAmount);
// Очень внимательно нужно менять значения, т.к. для второй стадии 1000%, чтобы учесть дробные значения
uint bonusPercentage = 0;
uint bonusStateMultiplier = 1;
// если запущена первая стадия, в конструкторе уже выпустили нужное кол-во токенов для первой стадии
if (currentState == State.FirstStageFunding){
// меньше 25000$ не принимаем
require(amountInCents >= 2500000);
// [25000$ - 50000$) - 50% бонуса
if (amountInCents >= 2500000 && amountInCents < 5000000){
bonusPercentage = 50;
// [50000$ - 100000$) - 75% бонуса
}else if(amountInCents >= 5000000 && amountInCents < 10000000){
bonusPercentage = 75;
// >= 100000$ - 100% бонуса
}else if(amountInCents >= 10000000){
bonusPercentage = 100;
}else{
revert();
}
// если запущена вторая стадия
} else if(currentState == State.SecondStageFunding){
// Процент проданных токенов, будем считать с множителем 10, т.к. есть дробные значения
bonusStateMultiplier = 10;
// Кол-во проданных токенов нужно считать от значения тех токенов, которые предназначены для продаж, т.е. secondStageTokensForSale
uint tokensSoldPercentage = secondStageTokensSold.mul(100).div(secondStageTokensForSale.mul(tokenMultiplier));
// меньше 7$ не принимаем
require(amountInCents >= 700);
// (0% - 10%) - 20% бонуса
if (tokensSoldPercentage >= 0 && tokensSoldPercentage < 10){
bonusPercentage = 200;
// [10% - 20%) - 17.5% бонуса
}else if (tokensSoldPercentage >= 10 && tokensSoldPercentage < 20){
bonusPercentage = 175;
// [20% - 30%) - 15% бонуса
}else if (tokensSoldPercentage >= 20 && tokensSoldPercentage < 30){
bonusPercentage = 150;
// [30% - 40%) - 12.5% бонуса
}else if (tokensSoldPercentage >= 30 && tokensSoldPercentage < 40){
bonusPercentage = 125;
// [40% - 50%) - 10% бонуса
}else if (tokensSoldPercentage >= 40 && tokensSoldPercentage < 50){
bonusPercentage = 100;
// [50% - 60%) - 8% бонуса
}else if (tokensSoldPercentage >= 50 && tokensSoldPercentage < 60){
bonusPercentage = 80;
// [60% - 70%) - 6% бонуса
}else if (tokensSoldPercentage >= 60 && tokensSoldPercentage < 70){
bonusPercentage = 60;
// [70% - 80%) - 4% бонуса
}else if (tokensSoldPercentage >= 70 && tokensSoldPercentage < 80){
bonusPercentage = 40;
// [80% - 90%) - 2% бонуса
}else if (tokensSoldPercentage >= 80 && tokensSoldPercentage < 90){
bonusPercentage = 20;
// >= 90% - 0% бонуса
}else if (tokensSoldPercentage >= 90){
bonusPercentage = 0;
}else{
revert();
}
} else revert();
// сколько токенов нужно выдать без бонуса
uint resultValue = amountInCents.mul(tokenMultiplier).div(oneTokenInCents);
// с учетом бонуса
uint tokenAmount = resultValue.mul(bonusStateMultiplier.mul(100).add(bonusPercentage)).div(bonusStateMultiplier.mul(100));
// краевой случай, когда запросили больше, чем можем выдать
uint tokensLeft = getTokensLeftForSale(currentState);
if (tokenAmount > tokensLeft){
tokenAmount = tokensLeft;
}
// Кол-во 0?, делаем откат
require(tokenAmount != 0);
// Новый инвестор?
if (investedAmountOf[receiver] == 0) {
investorCount++;
}
// Кидаем токены инвестору
internalAssignTokens(receiver, tokenAmount, weiAmount, amountInCents, txId);
// Обновляем статистику
updateStat(currentState, receiver, tokenAmount, weiAmount);
// Шлем на кошелёк эфир
// Функция - прослойка для возможности переопределения в дочерних классах
// Если это внешний вызов, то депозит не кладем
if (txId == 0){
internalDeposit(destinationMultisigWallet, weiAmount);
}
// Может переопределяеться в наследниках
}
/**
* Низкоуровневая функция перевода эфира на контракт, функция доступна для переопределения в дочерних классах, но не публична
*/
function internalDeposit(address receiver, uint weiAmount) internal{
// Переопределяется в наследниках
}
/**
* Низкоуровневая функция для возврата средств, функция доступна для переопределения в дочерних классах, но не публична
*/
function internalRefund(address receiver, uint weiAmount) internal{
// Переопределяется в наследниках
}
/**
* Низкоуровневая функция для включения режима возврата средств
*/
function internalEnableRefunds() internal{
// Переопределяется в наследниках
}
/**
* Спец. функция, которая позволяет продавать токены вне ценовой политики, доступка только владельцу
* Результаты пишутся в общую статистику, без разделения на стадии
* @param receiver - получатель
* @param tokenAmount - общее кол-во токенов c decimals!!!
* @param weiAmount - цена в wei
*/
function internalPreallocate(State currentState, address receiver, uint tokenAmount, uint weiAmount) internal {
// Cколько токенов осталось для продажи? Больше этого значения выдать не можем!
require(getTokensLeftForSale(currentState) >= tokenAmount);
// Может быть 0, выдаем токены бесплатно
internalAssignTokens(receiver, tokenAmount, weiAmount, getWeiInCents(weiAmount), 0);
// Обновляем статистику
updateStat(currentState, receiver, tokenAmount, weiAmount);
// Может переопределяеться в наследниках
}
/**
* Низкоуровневая функция для действий, в случае успеха
*/
function internalSuccessOver() internal {
// Переопределяется в наследниках
}
/**
* Функция, которая переопределяется в надледниках и выполняется после установки адреса аккаунта для перевода средств
*/
function internalSetDestinationMultisigWallet(address destinationAddress) internal{
}
/**
* Обновляем статистику для первой или второй стадии
*/
function updateStat(State currentState, address receiver, uint tokenAmount, uint weiAmount) private{
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
// Если это первая стадия
if (currentState == State.FirstStageFunding){
// Увеличиваем стату
firstStageRaisedInWei = firstStageRaisedInWei.add(weiAmount);
firstStageTokensSold = firstStageTokensSold.add(tokenAmount);
}
// Если это вторая стадия
if (currentState == State.SecondStageFunding){
// Увеличиваем стату
secondStageRaisedInWei = secondStageRaisedInWei.add(weiAmount);
secondStageTokensSold = secondStageTokensSold.add(tokenAmount);
}
investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount);
}
/**
* Функция, которая позволяет менять адрес аккаунта, куда будут переведены средства, в случае успеха,
* менять может только владелец и только в случае если продажи еще не завершены успехом
*/
function setDestinationMultisigWallet(address destinationAddress) public onlyOwner canSetDestinationMultisigWallet{
destinationMultisigWallet = destinationAddress;
internalSetDestinationMultisigWallet(destinationAddress);
}
/**
* Функция, которая задает текущий курс eth в центах
*/
function changeCurrentEtherRateInCents(uint value) public onlyOwner {
// Если случайно задали 0, не откатываем транзакцию
require(value > 0);
currentEtherRateInCents = value;
ExchangeRateChanged(currentEtherRateInCents, value);
}
/**
* Разделил на 2 метода, чтобы не запутаться при вызове
* Эти функции нужны в 2-х случаях: немного не собрали до Cap'а, сами докидываем необходимую сумму, есть приватные инвесторы, для которых существуют особые условия
*/
/* Для первой стадии */
function preallocateFirstStage(address receiver, uint tokenAmount, uint weiAmount) public onlyOwner isFirstStageFundingOrEnd {
internalPreallocate(State.FirstStageFunding, receiver, tokenAmount, weiAmount);
}
/* Для второй стадии, выдать можем не больше остатка для продажи */
function preallocateSecondStage(address receiver, uint tokenAmount, uint weiAmount) public onlyOwner isSecondStageFundingOrEnd {
internalPreallocate(State.SecondStageFunding, receiver, tokenAmount, weiAmount);
}
/* В случае успеха, заблокированные токены для команды могут быть востребованы только если наступила определенная дата */
function issueTeamTokens() public onlyOwner inState(State.Success) {
require(block.timestamp >= teamTokensIssueDate);
uint teamTokenTransferAmount = teamTokenAmount.mul(10 ** token.decimals());
if (!token.transfer(teamAccount, teamTokenTransferAmount)) revert();
}
/**
* Включает режим возвратов, только в случае если режим возврата еще не установлен и продажи не завершены успехом
* Вызвать можно только 1 раз
*/
function enableRefunds() public onlyOwner canEnableRefunds{
isRefundingEnabled = true;
// Сжигаем остатки на балансе текущего контракта
token.burnAllOwnerTokens();
internalEnableRefunds();
}
/**
* Покупка токенов, кидаем токены на адрес отправителя
*/
function buy() public payable {
internalInvest(msg.sender, msg.value, 0);
}
/**
* Покупка токенов через внешние системы
*/
function externalBuy(address buyerAddress, uint weiAmount, uint txId) external onlyOwner {
require(txId != 0);
internalInvest(buyerAddress, weiAmount, txId);
}
/**
* Инвесторы могут затребовать возврат средств, только в случае, если текущее состояние - Refunding
*/
function refund() public inState(State.Refunding) {
// Получаем значение, которое нам было переведено в эфире
uint weiValue = investedAmountOf[msg.sender];
require(weiValue != 0);
// Кол-во токенов на балансе, берем 2 значения: контракт продаж и контракт токена.
// Вернуть wei можем только тогда, когда эти значения совпадают, если не совпадают, значит были какие-то
// манипуляции с токенами и такие ситуации будут решаться в индивидуальном порядке, по запросу
uint saleContractTokenCount = tokenAmountOf[msg.sender];
uint tokenContractTokenCount = token.balanceOf(msg.sender);
require(saleContractTokenCount <= tokenContractTokenCount);
investedAmountOf[msg.sender] = 0;
weiRefunded = weiRefunded.add(weiValue);
// Событие генерируется в наследниках
internalRefund(msg.sender, weiValue);
}
/**
* Финализатор первой стадии, вызвать может только владелец при условии еще незавершившейся продажи
* Если вызван halt, то финализатор вызвать не можем
* Вызвать можно только 1 раз
*/
function finalizeFirstStage() public onlyOwner isNotSuccessOver {
require(!isFirstStageFinalized);
// Сжигаем остатки
// Всего можем продать firstStageTotalSupply
// Продали - firstStageTokensSold
// Все токены на балансе контракта сжигаем - это будет остаток
token.burnAllOwnerTokens();
// Переходим ко второй стадии
// Если повторно вызвать финализатор, то еще раз токены не создадутся, условие внутри
mintTokensForSecondStage();
isFirstStageFinalized = true;
}
/**
* Финализатор второй стадии, вызвать может только владелец, и только в случае финилизированной первой стадии
* и только в случае, если сборы еще не завершились успехом. Если вызван halt, то финализатор вызвать не можем.
* Вызвать можно только 1 раз
*/
function finalizeSecondStage() public onlyOwner isNotSuccessOver {
require(isFirstStageFinalized && !isSecondStageFinalized);
// Сжигаем остатки
// Всего можем продать secondStageTokensForSale
// Продали - secondStageTokensSold
// Разницу нужно сжечь, в любом случае
// Если достигнут Soft Cap, то считаем вторую стадию успешной
if (isSoftCapGoalReached()){
uint tokenMultiplier = 10 ** token.decimals();
uint remainingTokens = secondStageTokensForSale.mul(tokenMultiplier).sub(secondStageTokensSold);
// Если кол-во оставшихся токенов > 0, то сжигаем их
if (remainingTokens > 0){
token.burnOwnerTokens(remainingTokens);
}
// Переводим на подготовленные аккаунты: advisorsWalletAddress, marketingWalletAddress, teamWalletAddress
uint advisorsTokenTransferAmount = advisorsTokenAmount.mul(tokenMultiplier);
uint marketingTokenTransferAmount = marketingTokenAmount.mul(tokenMultiplier);
uint supportTokenTransferAmount = supportTokenAmount.mul(tokenMultiplier);
// Токены для команды заблокированы до даты teamTokensIssueDate и могут быть востребованы, только при вызове спец. функции
// issueTeamTokens
if (!token.transfer(advisorsAccount, advisorsTokenTransferAmount)) revert();
if (!token.transfer(marketingAccount, marketingTokenTransferAmount)) revert();
if (!token.transfer(supportAccount, supportTokenTransferAmount)) revert();
// Контракт выполнен!
isSuccessOver = true;
// Вызываем метод успеха
internalSuccessOver();
}else{
// Если не собрали Soft Cap, то сжигаем все токены на балансе контракта
token.burnAllOwnerTokens();
}
isSecondStageFinalized = true;
}
/**
* Позволяет менять владельцу даты стадий
*/
function setFirstStageStartsAt(uint time) public onlyOwner {
firstStageStartsAt = time;
// Вызываем событие
FirstStageStartsAtChanged(firstStageStartsAt);
}
function setFirstStageEndsAt(uint time) public onlyOwner {
firstStageEndsAt = time;
// Вызываем событие
FirstStageEndsAtChanged(firstStageEndsAt);
}
function setSecondStageStartsAt(uint time) public onlyOwner {
secondStageStartsAt = time;
// Вызываем событие
SecondStageStartsAtChanged(secondStageStartsAt);
}
function setSecondStageEndsAt(uint time) public onlyOwner {
secondStageEndsAt = time;
// Вызываем событие
SecondStageEndsAtChanged(secondStageEndsAt);
}
/**
* Позволяет менять владельцу Cap'ы
*/
function setSoftCapInCents(uint value) public onlyOwner {
require(value > 0);
softCapFundingGoalInCents = value;
// Вызываем событие
SoftCapChanged(softCapFundingGoalInCents);
}
function setHardCapInCents(uint value) public onlyOwner {
require(value > 0);
hardCapFundingGoalInCents = value;
// Вызываем событие
HardCapChanged(hardCapFundingGoalInCents);
}
/**
* Проверка сбора Soft Cap'а
*/
function isSoftCapGoalReached() public constant returns (bool) {
// Проверка по текущему курсу в центах, считает от общих продаж
return getWeiInCents(weiRaised) >= softCapFundingGoalInCents;
}
/**
* Проверка сбора Hard Cap'а
*/
function isHardCapGoalReached() public constant returns (bool) {
// Проверка по текущему курсу в центах, считает от общих продаж
return getWeiInCents(weiRaised) >= hardCapFundingGoalInCents;
}
/**
* Возвращает кол-во нераспроданных токенов, которые можно продать, в зависимости от стадии
*/
function getTokensLeftForSale(State forState) public constant returns (uint) {
// Кол-во токенов, которое адрес контракта можеть снять у owner'а и есть кол-во оставшихся токенов, из этой суммы нужно вычесть кол-во которое не участвует в продаже
uint tokenBalance = token.balanceOf(address(this));
uint tokensReserve = 0;
if (forState == State.SecondStageFunding) tokensReserve = secondStageReserve.mul(10 ** token.decimals());
if (tokenBalance <= tokensReserve){
return 0;
}
return tokenBalance.sub(tokensReserve);
}
/**
* Получаем стейт
*
* Не пишем в переменную, чтобы не было возможности поменять извне, только вызов функции может отразить текущее состояние
* См. граф состояний
*/
function getState() public constant returns (State) {
// Контракт выполнен
if (isSuccessOver) return State.Success;
// Контракт находится в режиме возврата
if (isRefundingEnabled) return State.Refunding;
// Контракт еще не начал действовать
if (block.timestamp < firstStageStartsAt) return State.PreFunding;
//Если первая стадия - не финализирована
if (!isFirstStageFinalized){
// Флаг того, что текущая дата находится в интервале первой стадии
bool isFirstStageTime = block.timestamp >= firstStageStartsAt && block.timestamp <= firstStageEndsAt;
// Если идет первая стадия
if (isFirstStageTime) return State.FirstStageFunding;
// Иначе первый этап - закончен
else return State.FirstStageEnd;
} else {
// Если первая стадия финализирована и текущее время блок чейна меньше начала второй стадии, то это означает, что первая стадия - окончена
if(block.timestamp < secondStageStartsAt)return State.FirstStageEnd;
// Флаг того, что текущая дата находится в интервале второй стадии
bool isSecondStageTime = block.timestamp >= secondStageStartsAt && block.timestamp <= secondStageEndsAt;
// Первая стадия финализирована, вторая - финализирована
if (isSecondStageFinalized){
// Если набрали Soft Cap при условии финализации второй сдадии - это успешное закрытие продаж
if (isSoftCapGoalReached())return State.Success;
// Собрать Soft Cap не удалось, текущее состояние - провал
else return State.Failure;
}else{
// Вторая стадия - не финализирована
if (isSecondStageTime)return State.SecondStageFunding;
// Вторая стадия - закончилась
else return State.SecondStageEnd;
}
}
}
/**
* Модификаторы
*/
/** Только, если текущее состояние соответсвует состоянию */
modifier inState(State state) {
require(getState() == state);
_;
}
/** Только, если текущее состояние - продажи: первая или вторая стадия */
modifier inFirstOrSecondFundingState() {
State curState = getState();
require(curState == State.FirstStageFunding || curState == State.SecondStageFunding);
_;
}
/** Только, если не достигнут Hard Cap */
modifier notHardCapReached(){
require(!isHardCapGoalReached());
_;
}
/** Только, если текущее состояние - продажи первой стадии или первая стадия закончилась */
modifier isFirstStageFundingOrEnd() {
State curState = getState();
require(curState == State.FirstStageFunding || curState == State.FirstStageEnd);
_;
}
/** Только, если контракт не финализирован */
modifier isNotSuccessOver() {
require(!isSuccessOver);
_;
}
/** Только, если идет вторая стадия или вторая стадия завершилась */
modifier isSecondStageFundingOrEnd() {
State curState = getState();
require(curState == State.SecondStageFunding || curState == State.SecondStageEnd);
_;
}
/** Только, если еще не включен режим возврата и продажи не завершены успехом */
modifier canEnableRefunds(){
require(!isRefundingEnabled && getState() != State.Success);
_;
}
/** Только, если продажи не завершены успехом */
modifier canSetDestinationMultisigWallet(){
require(getState() != State.Success);
_;
}
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* Шаблон класса хранилища средств, которое используется в контракте продаж
* Поддерживает возврат средств, а такте перевод средств на кошелек, в случае успешного проведения продаж
*/
contract FundsVault is Ownable, ValidationUtil {
using SafeMath for uint;
using Math for uint;
enum State {Active, Refunding, Closed}
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/**
* Указываем на какой кошелек будут потом переведены собранные средства, в случае, если будет вызвана функция close()
* Поддерживает возврат средств, а такте перевод средств на кошелек, в случае успешного проведения продаж
*/
function FundsVault(address _wallet) {
requireNotEmptyAddress(_wallet);
wallet = _wallet;
state = State.Active;
}
/**
* Положить депозит в хранилище
*/
function deposit(address investor) public payable onlyOwner inState(State.Active) {
deposited[investor] = deposited[investor].add(msg.value);
}
/**
* Перевод собранных средств на указанный кошелек
*/
function close() public onlyOwner inState(State.Active) {
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
/**
* Установливаем кошелек
*/
function setWallet(address newWalletAddress) public onlyOwner inState(State.Active) {
wallet = newWalletAddress;
}
/**
* Установить режим возврата денег
*/
function enableRefunds() public onlyOwner inState(State.Active) {
state = State.Refunding;
RefundsEnabled();
}
/**
* Функция возврата средств
*/
function refund(address investor, uint weiAmount) public onlyOwner inState(State.Refunding){
uint256 depositedValue = weiAmount.min256(deposited[investor]);
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
/** Только, если текущее состояние соответсвует состоянию */
modifier inState(State _state) {
require(state == _state);
_;
}
}
/**
* Контракт продажи
* Возврат средств поддержмвается только тем, кто купил токены через функцию internalInvest
* Таким образом, если инвесторы будут обмениваться токенами, то вернуть можно будет только тем, у кого в контракте продаж
* такая же сумма токенов, как и в контракте токена, в противном случае переведенный эфир остается навсегда в системе и не может быть выведен
*/
contract RefundableAllocatedCappedCrowdsale is AllocatedCappedCrowdsale {
/**
* Хранилище, куда будут собираться средства, делается для того, чтобы гарантировать возвраты
*/
FundsVault public fundsVault;
/** Мапа адрес инвестора - был ли совершен возврат среств */
mapping (address => bool) public refundedInvestors;
function RefundableAllocatedCappedCrowdsale(uint _currentEtherRateInCents, address _token, address _destinationMultisigWallet, uint _firstStageStartsAt, uint _firstStageEndsAt, uint _secondStageStartsAt, uint _secondStageEndsAt, address _advisorsAccount, address _marketingAccount, address _supportAccount, address _teamAccount, uint _teamTokensIssueDate) AllocatedCappedCrowdsale(_currentEtherRateInCents, _token, _destinationMultisigWallet, _firstStageStartsAt, _firstStageEndsAt, _secondStageStartsAt, _secondStageEndsAt, _advisorsAccount, _marketingAccount, _supportAccount, _teamAccount, _teamTokensIssueDate) {
// Создаем от контракта продаж новое хранилище, доступ к нему имеет только контракт продаж
// При успешном завершении продаж, все собранные средства поступят на _destinationMultisigWallet
// В противном случае могут быть переведены обратно инвесторам
fundsVault = new FundsVault(_destinationMultisigWallet);
}
/** Устанавливаем новый кошелек для финального перевода
*/
function internalSetDestinationMultisigWallet(address destinationAddress) internal{
fundsVault.setWallet(destinationAddress);
super.internalSetDestinationMultisigWallet(destinationAddress);
}
/** Финализация второго этапа
*/
function internalSuccessOver() internal {
// Успешно закрываем хранилище средств и переводим эфир на указанный кошелек
fundsVault.close();
super.internalSuccessOver();
}
/** Переопределение функции принятия допозита на счет, в данном случае, идти будет через vault
*/
function internalDeposit(address receiver, uint weiAmount) internal{
// Шлем на кошелёк эфир
fundsVault.deposit.value(weiAmount)(msg.sender);
}
/** Переопределение функции включения состояния возврата
*/
function internalEnableRefunds() internal{
super.internalEnableRefunds();
fundsVault.enableRefunds();
}
/** Переопределение функции возврата, возврат можно сделать только раз
*/
function internalRefund(address receiver, uint weiAmount) internal{
// Делаем возврат
// Поддерживаем только 1 возврат
if (refundedInvestors[receiver]) revert();
fundsVault.refund(receiver, weiAmount);
refundedInvestors[receiver] = true;
}
} | Положить депозит в хранилище/ | function deposit(address investor) public payable onlyOwner inState(State.Active) {
deposited[investor] = deposited[investor].add(msg.value);
}
| 13,009,173 |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, 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.
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/strategies/IAave.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for Aaves Lending Pool
* Documentation: https://developers.aave.com/#lendingpool
*/
interface IAaveLendingPool {
/**
* @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 Interface for Aaves Lending Pool
* Documentation: https://developers.aave.com/#lendingpooladdressesprovider
*/
interface ILendingPoolAddressesProvider {
/**
* @notice Get the current address for Aave LendingPool
* @dev Lending pool is the core contract on which to call deposit
*/
function getLendingPool() external view returns (address);
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: contracts/utils/Initializable.sol
pragma solidity ^0.8.0;
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;
}
}
uint256[50] private ______gap;
}
// File: contracts/governance/Governable.sol
pragma solidity ^0.8.0;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
// keccak256("OUSD.governor");
bytes32 private constant governorPosition =
0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
// keccak256("OUSD.pending.governor");
bytes32 private constant pendingGovernorPosition =
0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
// keccak256("OUSD.reentry.status");
bytes32 private constant reentryStatusPosition =
0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535;
// See OpenZeppelin ReentrancyGuard implementation
uint256 constant _NOT_ENTERED = 1;
uint256 constant _ENTERED = 2;
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
/**
* @dev Returns the address of the current Governor.
*/
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
/**
* @dev Returns the address of the pending Governor.
*/
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
bytes32 position = reentryStatusPosition;
uint256 _reentry_status;
assembly {
_reentry_status := sload(position)
}
// On the first call to nonReentrant, _notEntered will be true
require(_reentry_status != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
assembly {
sstore(position, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(position, _NOT_ENTERED)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: contracts/utils/InitializableAbstractStrategy.sol
pragma solidity ^0.8.0;
abstract contract InitializableAbstractStrategy is Initializable, Governable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
event PTokenAdded(address indexed _asset, address _pToken);
event PTokenRemoved(address indexed _asset, address _pToken);
event Deposit(address indexed _asset, address _pToken, uint256 _amount);
event Withdrawal(address indexed _asset, address _pToken, uint256 _amount);
event RewardTokenCollected(address recipient, uint256 amount);
event RewardTokenAddressUpdated(address _oldAddress, address _newAddress);
event RewardLiquidationThresholdUpdated(
uint256 _oldThreshold,
uint256 _newThreshold
);
// Core address for the given platform
address public platformAddress;
address public vaultAddress;
// asset => pToken (Platform Specific Token Address)
mapping(address => address) public assetToPToken;
// Full list of all assets supported here
address[] internal assetsMapped;
// Reward token address
address public rewardTokenAddress;
uint256 public rewardLiquidationThreshold;
// Reserved for future expansion
int256[100] private _reserved;
/**
* @dev Internal initialize function, to set up initial internal state
* @param _platformAddress Generic platform address
* @param _vaultAddress Address of the Vault
* @param _rewardTokenAddress Address of reward token for platform
* @param _assets Addresses of initial supported assets
* @param _pTokens Platform Token corresponding addresses
*/
function initialize(
address _platformAddress,
address _vaultAddress,
address _rewardTokenAddress,
address[] calldata _assets,
address[] calldata _pTokens
) external onlyGovernor initializer {
InitializableAbstractStrategy._initialize(
_platformAddress,
_vaultAddress,
_rewardTokenAddress,
_assets,
_pTokens
);
}
function _initialize(
address _platformAddress,
address _vaultAddress,
address _rewardTokenAddress,
address[] memory _assets,
address[] memory _pTokens
) internal {
platformAddress = _platformAddress;
vaultAddress = _vaultAddress;
rewardTokenAddress = _rewardTokenAddress;
uint256 assetCount = _assets.length;
require(assetCount == _pTokens.length, "Invalid input arrays");
for (uint256 i = 0; i < assetCount; i++) {
_setPTokenAddress(_assets[i], _pTokens[i]);
}
}
/**
* @dev Collect accumulated reward token and send to Vault.
*/
function collectRewardToken() external virtual onlyVault nonReentrant {
IERC20 rewardToken = IERC20(rewardTokenAddress);
uint256 balance = rewardToken.balanceOf(address(this));
emit RewardTokenCollected(vaultAddress, balance);
rewardToken.safeTransfer(vaultAddress, balance);
}
/**
* @dev Verifies that the caller is the Vault.
*/
modifier onlyVault() {
require(msg.sender == vaultAddress, "Caller is not the Vault");
_;
}
/**
* @dev Verifies that the caller is the Vault or Governor.
*/
modifier onlyVaultOrGovernor() {
require(
msg.sender == vaultAddress || msg.sender == governor(),
"Caller is not the Vault or Governor"
);
_;
}
/**
* @dev Set the reward token address.
* @param _rewardTokenAddress Address of the reward token
*/
function setRewardTokenAddress(address _rewardTokenAddress)
external
onlyGovernor
{
emit RewardTokenAddressUpdated(rewardTokenAddress, _rewardTokenAddress);
rewardTokenAddress = _rewardTokenAddress;
}
/**
* @dev Set the reward token liquidation threshold.
* @param _threshold Threshold amount in decimals of reward token that will
* cause the Vault to claim and withdrawAll on allocate() calls.
*/
function setRewardLiquidationThreshold(uint256 _threshold)
external
onlyGovernor
{
emit RewardLiquidationThresholdUpdated(
rewardLiquidationThreshold,
_threshold
);
rewardLiquidationThreshold = _threshold;
}
/**
* @dev Provide support for asset by passing its pToken address.
* This method can only be called by the system Governor
* @param _asset Address for the asset
* @param _pToken Address for the corresponding platform token
*/
function setPTokenAddress(address _asset, address _pToken)
external
onlyGovernor
{
_setPTokenAddress(_asset, _pToken);
}
/**
* @dev Remove a supported asset by passing its index.
* This method can only be called by the system Governor
* @param _assetIndex Index of the asset to be removed
*/
function removePToken(uint256 _assetIndex) external onlyGovernor {
require(_assetIndex < assetsMapped.length, "Invalid index");
address asset = assetsMapped[_assetIndex];
address pToken = assetToPToken[asset];
if (_assetIndex < assetsMapped.length - 1) {
assetsMapped[_assetIndex] = assetsMapped[assetsMapped.length - 1];
}
assetsMapped.pop();
assetToPToken[asset] = address(0);
emit PTokenRemoved(asset, pToken);
}
/**
* @dev Provide support for asset by passing its pToken address.
* Add to internal mappings and execute the platform specific,
* abstract method `_abstractSetPToken`
* @param _asset Address for the asset
* @param _pToken Address for the corresponding platform token
*/
function _setPTokenAddress(address _asset, address _pToken) internal {
require(assetToPToken[_asset] == address(0), "pToken already set");
require(
_asset != address(0) && _pToken != address(0),
"Invalid addresses"
);
assetToPToken[_asset] = _pToken;
assetsMapped.push(_asset);
emit PTokenAdded(_asset, _pToken);
_abstractSetPToken(_asset, _pToken);
}
/**
* @dev Transfer token to governor. Intended for recovering tokens stuck in
* strategy contracts, i.e. mistaken sends.
* @param _asset Address for the asset
* @param _amount Amount of the asset to transfer
*/
function transferToken(address _asset, uint256 _amount)
public
onlyGovernor
{
IERC20(_asset).safeTransfer(governor(), _amount);
}
/***************************************
Abstract
****************************************/
function _abstractSetPToken(address _asset, address _pToken)
internal
virtual;
function safeApproveAllTokens() external virtual;
/**
* @dev Deposit an amount of asset into the platform
* @param _asset Address for the asset
* @param _amount Units of asset to deposit
*/
function deposit(address _asset, uint256 _amount) external virtual;
/**
* @dev Deposit balance of all supported assets into the platform
*/
function depositAll() external virtual;
/**
* @dev Withdraw an amount of asset from the platform.
* @param _recipient Address to which the asset should be sent
* @param _asset Address of the asset
* @param _amount Units of asset to withdraw
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external virtual;
/**
* @dev Withdraw all assets from strategy sending assets to Vault.
*/
function withdrawAll() external virtual;
/**
* @dev Get the total asset value held in the platform.
* This includes any interest that was generated since depositing.
* @param _asset Address of the asset
* @return balance Total value of the asset in the platform
*/
function checkBalance(address _asset)
external
view
virtual
returns (uint256 balance);
/**
* @dev Check if an asset is supported.
* @param _asset Address of the asset
* @return bool Whether asset is supported
*/
function supportsAsset(address _asset) external view virtual returns (bool);
}
// File: contracts/strategies/IAaveStakeToken.sol
pragma solidity ^0.8.0;
interface IAaveStakedToken {
function COOLDOWN_SECONDS() external returns (uint256);
function UNSTAKE_WINDOW() external returns (uint256);
function balanceOf(address addr) external returns (uint256);
function redeem(address to, uint256 amount) external;
function stakersCooldowns(address addr) external returns (uint256);
function cooldown() external;
}
// File: contracts/strategies/IAaveIncentivesController.sol
pragma solidity ^0.8.0;
interface IAaveIncentivesController {
event RewardsAccrued(address indexed user, uint256 amount);
event RewardsClaimed(
address indexed user,
address indexed to,
uint256 amount
);
event RewardsClaimed(
address indexed user,
address indexed to,
address indexed claimer,
uint256 amount
);
event ClaimerSet(address indexed user, address indexed claimer);
/*
* @dev Returns the configuration of the distribution for a certain asset
* @param asset The address of the reference asset of the distribution
* @return The asset index, the emission per second and the last updated timestamp
**/
function getAssetData(address asset)
external
view
returns (
uint256,
uint256,
uint256
);
/**
* @dev Whitelists an address to claim the rewards on behalf of another address
* @param user The address of the user
* @param claimer The address of the claimer
*/
function setClaimer(address user, address claimer) external;
/**
* @dev Returns the whitelisted claimer for a certain address (0x0 if not set)
* @param user The address of the user
* @return The claimer address
*/
function getClaimer(address user) external view returns (address);
/**
* @dev Configure assets for a certain rewards emission
* @param assets The assets to incentivize
* @param emissionsPerSecond The emission for each asset
*/
function configureAssets(
address[] calldata assets,
uint256[] calldata emissionsPerSecond
) external;
/**
* @dev Called by the corresponding asset on any update that affects the rewards distribution
* @param asset The address of the user
* @param userBalance The balance of the user of the asset in the lending pool
* @param totalSupply The total supply of the asset in the lending pool
**/
function handleAction(
address asset,
uint256 userBalance,
uint256 totalSupply
) external;
/**
* @dev Returns the total of rewards of an user, already accrued + not yet accrued
* @param user The address of the user
* @return The rewards
**/
function getRewardsBalance(address[] calldata assets, address user)
external
view
returns (uint256);
/**
* @dev Claims reward for an user, on all the assets of the lending pool,
* accumulating the pending rewards
* @param amount Amount of rewards to claim
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Claims reward for an user on behalf, on all the assets of the
* lending pool, accumulating the pending rewards. The caller must
* be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param amount Amount of rewards to claim
* @param user Address to check and claim rewards
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewardsOnBehalf(
address[] calldata assets,
uint256 amount,
address user,
address to
) external returns (uint256);
/**
* @dev returns the unclaimed rewards of the user
* @param user the address of the user
* @return the unclaimed user rewards
*/
function getUserUnclaimedRewards(address user)
external
view
returns (uint256);
/**
* @dev returns the unclaimed rewards of the user
* @param user the address of the user
* @param asset The asset to incentivize
* @return the user index for the asset
*/
function getUserAssetData(address user, address asset)
external
view
returns (uint256);
/**
* @dev for backward compatibility with previous implementation of the Incentives controller
*/
function REWARD_TOKEN() external view returns (address);
/**
* @dev for backward compatibility with previous implementation of the Incentives controller
*/
function PRECISION() external view returns (uint8);
/**
* @dev Gets the distribution end timestamp of the emissions
*/
function DISTRIBUTION_END() external view returns (uint256);
}
// File: contracts/strategies/AaveStrategy.sol
pragma solidity ^0.8.0;
/**
* @title OUSD Aave Strategy
* @notice Investment strategy for investing stablecoins via Aave
* @author Origin Protocol Inc
*/
contract AaveStrategy is InitializableAbstractStrategy {
using SafeERC20 for IERC20;
uint16 constant referralCode = 92;
IAaveIncentivesController public incentivesController;
IAaveStakedToken public stkAave;
/**
* Initializer for setting up strategy internal state. This overrides the
* InitializableAbstractStrategy initializer as AAVE needs several extra
* addresses for the rewards program.
* @param _platformAddress Address of the AAVE pool
* @param _vaultAddress Address of the vault
* @param _rewardTokenAddress Address of the AAVE token
* @param _assets Addresses of supported assets
* @param _pTokens Platform Token corresponding addresses
* @param _incentivesAddress Address of the AAVE incentives controller
* @param _stkAaveAddress Address of the stkAave contract
*/
function initialize(
address _platformAddress, // AAVE pool
address _vaultAddress,
address _rewardTokenAddress, // AAVE
address[] calldata _assets,
address[] calldata _pTokens,
address _incentivesAddress,
address _stkAaveAddress
) external onlyGovernor initializer {
incentivesController = IAaveIncentivesController(_incentivesAddress);
stkAave = IAaveStakedToken(_stkAaveAddress);
InitializableAbstractStrategy._initialize(
_platformAddress,
_vaultAddress,
_rewardTokenAddress,
_assets,
_pTokens
);
}
/**
* @dev Deposit asset into Aave
* @param _asset Address of asset to deposit
* @param _amount Amount of asset to deposit
*/
function deposit(address _asset, uint256 _amount)
external
override
onlyVault
nonReentrant
{
_deposit(_asset, _amount);
}
/**
* @dev Deposit asset into Aave
* @param _asset Address of asset to deposit
* @param _amount Amount of asset to deposit
*/
function _deposit(address _asset, uint256 _amount) internal {
require(_amount > 0, "Must deposit something");
// Following line also doubles as a check that we are depositing
// an asset that we support.
emit Deposit(_asset, _getATokenFor(_asset), _amount);
_getLendingPool().deposit(_asset, _amount, address(this), referralCode);
}
/**
* @dev Deposit the entire balance of any supported asset into Aave
*/
function depositAll() external override onlyVault nonReentrant {
for (uint256 i = 0; i < assetsMapped.length; i++) {
uint256 balance = IERC20(assetsMapped[i]).balanceOf(address(this));
if (balance > 0) {
_deposit(assetsMapped[i], balance);
}
}
}
/**
* @dev Withdraw asset from Aave
* @param _recipient Address to receive withdrawn asset
* @param _asset Address of asset to withdraw
* @param _amount Amount of asset to withdraw
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external override onlyVault nonReentrant {
require(_amount > 0, "Must withdraw something");
require(_recipient != address(0), "Must specify recipient");
emit Withdrawal(_asset, _getATokenFor(_asset), _amount);
uint256 actual = _getLendingPool().withdraw(
_asset,
_amount,
address(this)
);
require(actual == _amount, "Did not withdraw enough");
IERC20(_asset).safeTransfer(_recipient, _amount);
}
/**
* @dev Remove all assets from platform and send them to Vault contract.
*/
function withdrawAll() external override onlyVaultOrGovernor nonReentrant {
for (uint256 i = 0; i < assetsMapped.length; i++) {
// Redeem entire balance of aToken
IERC20 asset = IERC20(assetsMapped[i]);
address aToken = _getATokenFor(assetsMapped[i]);
uint256 balance = IERC20(aToken).balanceOf(address(this));
if (balance > 0) {
uint256 actual = _getLendingPool().withdraw(
address(asset),
balance,
address(this)
);
require(actual == balance, "Did not withdraw enough");
// Transfer entire balance to Vault
asset.safeTransfer(
vaultAddress,
asset.balanceOf(address(this))
);
}
}
}
/**
* @dev Get the total asset value held in the platform
* @param _asset Address of the asset
* @return balance Total value of the asset in the platform
*/
function checkBalance(address _asset)
external
view
override
returns (uint256 balance)
{
// Balance is always with token aToken decimals
address aToken = _getATokenFor(_asset);
balance = IERC20(aToken).balanceOf(address(this));
}
/**
* @dev Retuns bool indicating whether asset is supported by strategy
* @param _asset Address of the asset
*/
function supportsAsset(address _asset)
external
view
override
returns (bool)
{
return assetToPToken[_asset] != address(0);
}
/**
* @dev Approve the spending of all assets by their corresponding aToken,
* if for some reason is it necessary.
*/
function safeApproveAllTokens()
external
override
onlyGovernor
nonReentrant
{
address lendingPool = address(_getLendingPool());
// approve the pool to spend the Asset
for (uint256 i = 0; i < assetsMapped.length; i++) {
address asset = assetsMapped[i];
// Safe approval
IERC20(asset).safeApprove(lendingPool, 0);
IERC20(asset).safeApprove(lendingPool, type(uint256).max);
}
}
/**
* @dev Internal method to respond to the addition of new asset / aTokens
We need to give the AAVE lending pool approval to transfer the
asset.
* @param _asset Address of the asset to approve
* @param _aToken Address of the aToken
*/
function _abstractSetPToken(address _asset, address _aToken)
internal
override
{
address lendingPool = address(_getLendingPool());
IERC20(_asset).safeApprove(lendingPool, 0);
IERC20(_asset).safeApprove(lendingPool, type(uint256).max);
}
/**
* @dev Get the aToken wrapped in the IERC20 interface for this asset.
* Fails if the pToken doesn't exist in our mappings.
* @param _asset Address of the asset
* @return Corresponding aToken to this asset
*/
function _getATokenFor(address _asset) internal view returns (address) {
address aToken = assetToPToken[_asset];
require(aToken != address(0), "aToken does not exist");
return aToken;
}
/**
* @dev Get the current address of the Aave lending pool, which is the gateway to
* depositing.
* @return Current lending pool implementation
*/
function _getLendingPool() internal view returns (IAaveLendingPool) {
address lendingPool = ILendingPoolAddressesProvider(platformAddress)
.getLendingPool();
require(lendingPool != address(0), "Lending pool does not exist");
return IAaveLendingPool(lendingPool);
}
/**
* @dev Collect stkAave, convert it to AAVE send to Vault.
*/
function collectRewardToken() external override onlyVault nonReentrant {
if (address(stkAave) == address(0)) {
return;
}
// Check staked AAVE cooldown timer
uint256 cooldown = stkAave.stakersCooldowns(address(this));
uint256 windowStart = cooldown + stkAave.COOLDOWN_SECONDS();
uint256 windowEnd = windowStart + stkAave.UNSTAKE_WINDOW();
// If inside the unlock window, then we can redeem stkAave
// for AAVE and send it to the vault.
if (block.timestamp > windowStart && block.timestamp <= windowEnd) {
// Redeem to AAVE
uint256 stkAaveBalance = stkAave.balanceOf(address(this));
if (stkAaveBalance > rewardLiquidationThreshold) {
stkAave.redeem(address(this), stkAaveBalance);
}
// Transfer AAVE to vaultAddress
uint256 aaveBalance = IERC20(rewardTokenAddress).balanceOf(
address(this)
);
if (aaveBalance > 0) {
IERC20(rewardTokenAddress).safeTransfer(
vaultAddress,
aaveBalance
);
}
}
// Collect avaiable rewards and restart the cooldown timer, if either of
// those should be run.
if (block.timestamp > windowStart || cooldown == 0) {
// aToken addresses for incentives controller
address[] memory aTokens = new address[](assetsMapped.length);
for (uint256 i = 0; i < assetsMapped.length; i++) {
aTokens[i] = _getATokenFor(assetsMapped[i]);
}
// 1. If we have rewards availabile, collect them
uint256 pendingRewards = incentivesController.getRewardsBalance(
aTokens,
address(this)
);
if (pendingRewards > 0) {
// Because getting more stkAAVE from the incentives controller
// with claimRewards() may push the stkAAVE cooldown time
// forward, it is called after stakedAAVE has been turned into
// AAVE.
uint256 collected = incentivesController.claimRewards(
aTokens,
pendingRewards,
address(this)
);
require(collected == pendingRewards, "AAVE reward difference");
}
// 2. Start cooldown counting down.
if (stkAave.balanceOf(address(this)) > 0) {
// Protected with if since cooldown call would revert
// if no stkAave balance.
stkAave.cooldown();
}
}
}
}
| Deposit an amount of asset into the platform _asset Address for the asset _amount Units of asset to deposit/ Deposit balance of all supported assets into the platform/ Withdraw an amount of asset from the platform. _recipient Address to which the asset should be sent _asset Address of the asset _amount Units of asset to withdraw/ Withdraw all assets from strategy sending assets to Vault./ Get the total asset value held in the platform. This includes any interest that was generated since depositing. _asset Address of the asset return balance Total value of the asset in the platform/ Check if an asset is supported. _asset Address of the asset return bool Whether asset is supported/ File: contracts/strategies/IAaveStakeToken.sol | interface IAaveStakedToken {
function COOLDOWN_SECONDS() external returns (uint256);
function UNSTAKE_WINDOW() external returns (uint256);
function balanceOf(address addr) external returns (uint256);
function redeem(address to, uint256 amount) external;
function stakersCooldowns(address addr) external returns (uint256);
function cooldown() external;
}
| 11,949,698 |
pragma solidity 0.4.25;
// File: contracts/sogur/interfaces/IModelDataSource.sol
/**
* @title Model Data Source Interface.
*/
interface IModelDataSource {
/**
* @dev Get interval parameters.
* @param _rowNum Interval row index.
* @param _colNum Interval column index.
* @return Interval minimum amount of SGR.
* @return Interval maximum amount of SGR.
* @return Interval minimum amount of SDR.
* @return Interval maximum amount of SDR.
* @return Interval alpha value (scaled up).
* @return Interval beta value (scaled up).
*/
function getInterval(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
/**
* @dev Get interval alpha and beta.
* @param _rowNum Interval row index.
* @param _colNum Interval column index.
* @return Interval alpha value (scaled up).
* @return Interval beta value (scaled up).
*/
function getIntervalCoefs(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256);
/**
* @dev Get the amount of SGR required for moving to the next minting-point.
* @param _rowNum Interval row index.
* @return Required amount of SGR.
*/
function getRequiredMintAmount(uint256 _rowNum) external view returns (uint256);
}
// File: contracts/sogur/interfaces/IMintingPointTimersManager.sol
/**
* @title Minting Point Timers Manager Interface.
*/
interface IMintingPointTimersManager {
/**
* @dev Start a given timestamp.
* @param _id The ID of the timestamp.
* @notice When tested, this timestamp will be either 'running' or 'expired'.
*/
function start(uint256 _id) external;
/**
* @dev Reset a given timestamp.
* @param _id The ID of the timestamp.
* @notice When tested, this timestamp will be neither 'running' nor 'expired'.
*/
function reset(uint256 _id) external;
/**
* @dev Get an indication of whether or not a given timestamp is 'running'.
* @param _id The ID of the timestamp.
* @return An indication of whether or not a given timestamp is 'running'.
* @notice Even if this timestamp is not 'running', it is not necessarily 'expired'.
*/
function running(uint256 _id) external view returns (bool);
/**
* @dev Get an indication of whether or not a given timestamp is 'expired'.
* @param _id The ID of the timestamp.
* @return An indication of whether or not a given timestamp is 'expired'.
* @notice Even if this timestamp is not 'expired', it is not necessarily 'running'.
*/
function expired(uint256 _id) external view returns (bool);
}
// File: contracts/sogur/interfaces/IIntervalIterator.sol
/**
* @title Interval Iterator Interface.
*/
interface IIntervalIterator {
/**
* @dev Move to a higher interval and start a corresponding timer if necessary.
*/
function grow() external;
/**
* @dev Reset the timer of the current interval if necessary and move to a lower interval.
*/
function shrink() external;
/**
* @dev Return the current interval.
*/
function getCurrentInterval() external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
/**
* @dev Return the current interval coefficients.
*/
function getCurrentIntervalCoefs() external view returns (uint256, uint256);
}
// File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol
/**
* @title Contract Address Locator Interface.
*/
interface IContractAddressLocator {
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) external view returns (address);
/**
* @dev Determine whether or not a contract address relates to one of the identifiers.
* @param _contractAddress The contract address to look for.
* @param _identifiers The identifiers.
* @return A boolean indicating if the contract address relates to one of the identifiers.
*/
function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
}
// File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol
/**
* @title Contract Address Locator Holder.
* @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system.
* @dev Any contract which inherits from this contract can retrieve the address of any contract in the system.
* @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system.
* @dev In addition to that, any function in any contract can be restricted to a specific caller.
*/
contract ContractAddressLocatorHolder {
bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource";
bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ;
bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ;
bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ;
bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ;
bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ;
bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ;
bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ;
bytes32 internal constant _IMintHandler_ = "IMintHandler" ;
bytes32 internal constant _IMintListener_ = "IMintListener" ;
bytes32 internal constant _IMintManager_ = "IMintManager" ;
bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ;
bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ;
bytes32 internal constant _IRedButton_ = "IRedButton" ;
bytes32 internal constant _IReserveManager_ = "IReserveManager" ;
bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ;
bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ;
bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ;
bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ;
bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ;
bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager";
bytes32 internal constant _ISGRToken_ = "ISGRToken" ;
bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ;
bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ;
bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager";
bytes32 internal constant _ISGNToken_ = "ISGNToken" ;
bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ;
bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ;
bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ;
bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ;
bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ;
bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ;
bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ;
bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ;
bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ;
bytes32 internal constant _IETHConverter_ = "IETHConverter" ;
bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ;
bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ;
bytes32 internal constant _IRateApprover_ = "IRateApprover" ;
bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ;
IContractAddressLocator private contractAddressLocator;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) internal {
require(_contractAddressLocator != address(0), "locator is illegal");
contractAddressLocator = _contractAddressLocator;
}
/**
* @dev Get the contract address locator.
* @return The contract address locator.
*/
function getContractAddressLocator() external view returns (IContractAddressLocator) {
return contractAddressLocator;
}
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) internal view returns (address) {
return contractAddressLocator.getContractAddress(_identifier);
}
/**
* @dev Determine whether or not the sender relates to one of the identifiers.
* @param _identifiers The identifiers.
* @return A boolean indicating if the sender relates to one of the identifiers.
*/
function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) {
return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers);
}
/**
* @dev Verify that the caller is mapped to a given identifier.
* @param _identifier The identifier.
*/
modifier only(bytes32 _identifier) {
require(msg.sender == getContractAddress(_identifier), "caller is illegal");
_;
}
}
// File: contracts/sogur/IntervalIterator.sol
/**
* Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1
*/
/**
* @title Interval Iterator.
*/
contract IntervalIterator is IIntervalIterator, ContractAddressLocatorHolder {
string public constant VERSION = "1.0.1";
uint256 public constant MAX_GROW_ROW = 94;
uint256 public row;
uint256 public col;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
/**
* @dev Return the contract which implements the IModelDataSource interface.
*/
function getModelDataSource() public view returns (IModelDataSource) {
return IModelDataSource(getContractAddress(_IModelDataSource_));
}
/**
* @dev Return the contract which implements the IMintingPointTimersManager interface.
*/
function getMintingPointTimersManager() public view returns (IMintingPointTimersManager) {
return IMintingPointTimersManager(getContractAddress(_IMintingPointTimersManager_));
}
/**
* @dev Move to a higher interval and start a corresponding timer if necessary.
*/
function grow() external only(_IMonetaryModel_) {
if (col == 0) {
row += 1;
require(row <= MAX_GROW_ROW, "reached end of last interval");
getMintingPointTimersManager().start(row);
}
else {
col -= 1;
}
}
/**
* @dev Reset the timer of the current interval if necessary and move to a lower interval.
*/
function shrink() external only(_IMonetaryModel_) {
IMintingPointTimersManager mintingPointTimersManager = getMintingPointTimersManager();
if (mintingPointTimersManager.running(row)) {
mintingPointTimersManager.reset(row);
assert(row > 0);
row -= 1;
}
else {
col += 1;
}
}
/**
* @dev Return the current interval.
*/
function getCurrentInterval() external view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
return getModelDataSource().getInterval(row, col);
}
/**
* @dev Return the current interval coefficients.
*/
function getCurrentIntervalCoefs() external view returns (uint256, uint256) {
return getModelDataSource().getIntervalCoefs(row, col);
}
} | Return the contract which implements the IMintingPointTimersManager interface./ | function getMintingPointTimersManager() public view returns (IMintingPointTimersManager) {
return IMintingPointTimersManager(getContractAddress(_IMintingPointTimersManager_));
}
| 2,074,775 |
./partial_match/1/0x67391801E7564994bdAa80544Ff916A7bCBFCB60/sources/MacroverseUniversalRegistry.sol | Calculate atan(x) for x in [-1, 1]. Uses the Chebyshev polynomial approach presented at Uses polynomials received by personal communication. 0.999974x-0.332568x^3+0.193235x^5-0.115729x^7+0.0519505x^9-0.0114658x^11/ | function atanSmall(int128 real_arg) public pure returns (int128) {
int128 real_arg_squared = mul(real_arg, real_arg);
return mul(mul(mul(mul(mul(mul(
}
| 9,236,747 |
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./ERC2981.sol";
import "./RoyaltiesAddon.sol";
contract NFT is RoyaltiesAddon, ERC2981, AccessControl {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
uint256 private royaltiesFees;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor(string memory name, string memory symbol)
ERC721(name, symbol)
{
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, ERC2981, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function addMinter(address minterAddress)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setupRole(MINTER_ROLE, minterAddress);
}
function removeMinter(address minterAddress)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
revokeRole(MINTER_ROLE, minterAddress);
}
function mint(address receiver, string memory metadata)
public
onlyRole(MINTER_ROLE)
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(receiver, newItemId);
_setTokenURI(newItemId, metadata);
return newItemId;
}
/// @dev sets royalties address
/// for royalties addon
/// for 2981
function setRoyaltiesAddress(address _royaltiesAddress)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
super._setRoyaltiesAddress(_royaltiesAddress);
}
/// @dev sets royalties fees
function setRoyaltiesFees(uint256 _royaltiesFees)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
royaltiesFees = _royaltiesFees;
}
/// @inheritdoc IERC2981
function royaltyInfo(uint256 tokenId, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
return (royaltiesAddress, value * royaltiesFees / 100);
}
}
| sets royalties address for royalties addon for 2981 | function setRoyaltiesAddress(address _royaltiesAddress)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
super._setRoyaltiesAddress(_royaltiesAddress);
}
| 6,486,216 |
./partial_match/1/0x7Cc46CF6392ed9DB45351A3F82EB2Cc3b83Da761/sources/contracts/DeepSeaCreatures.sol | burn by tokenIdtransfer back 0.5 BAIT to user for burning | function burn(uint256 tokenId) external {
require(isBurnable, "burning is not enabled");
_burn(tokenId, true);
baitToken.transfer(msg.sender, 0.5e18);
}
| 3,572,218 |
./full_match/1/0x7a91BC4C9308844446792B51b99F5d111178D42d/sources/contracts/Minter.sol | Add _token into the list, add _cToken in mapping and approve cToken to spend token/ | function _addToken(
address _token,
address _cToken,
address _oracle
) internal {
require(_whitelistedTokens.add(_token), "add-in-list-failed");
oracles[_token] = _oracle;
cTokens[_token] = _cToken;
IERC20(_token).safeApprove(_cToken, type(uint256).max);
}
| 9,622,303 |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_243(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,453,956 |
/**
*Submitted for verification at Etherscan.io on 2022-03-31
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev 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 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);
}
}
/**
* @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);
}
}
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @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);
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex = 1;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex - 1;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), 'ERC721A: global index out of bounds');
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert('ERC721A: unable to get token of owner by index');
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return uint256(_addressData[owner].numberMinted);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');
unchecked {
for (uint256 curr = tokenId; curr >= 0; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
revert('ERC721A: unable to determine the owner of token');
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token');
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : '';
}
/**
* @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 pure virtual returns (string memory) {
return "ipfs://QmfSidchfiREAif9BTazBni4pn86WueDN7YEv9pwoB9A8Q/";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, 'ERC721A: approval to current owner');
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
'ERC721A: approve caller is not owner nor approved for all'
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), 'ERC721A: approved query for nonexistent token');
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), 'ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex && tokenId > 0;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), 'ERC721A: mint to the zero address');
require(quantity != 0, 'ERC721A: quantity must be greater than 0');
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
updatedIndex++;
}
currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved');
require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner');
require(to != address(0), 'ERC721A: transfer to the zero address');
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721A: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
contract SmithPunks is ERC721A, Ownable {
constructor() ERC721A("Smith Punks", "SMITH") {
_safeMint(msg.sender, 30);
}
uint64 private constant MAX_PER_TX = 25;
uint64 private constant MAX_SUPPLY = 5000;
uint128 public constant PRICE = 0.003 ether;
function mint(uint256 amount) external payable {
require(amount <= MAX_PER_TX, "NOT_ALLOWED");
require(currentIndex + amount <= MAX_SUPPLY + 1, "EXCEEDS_MAX_SUPPLY!");
require(msg.value == PRICE * amount, "INCORRECT_VALUE!");
_safeMint(msg.sender, amount);
}
function withdraw() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
} | 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 pure virtual returns (string memory) {
}
| 7,880,307 |
./partial_match/1/0xD3faD4C5e4D24646F90A0c8876314b17243E9460/sources/contracts/KounPass.sol | Mint a quantity of tokens to the contract owners address Use restricted to contract owner _quantity Number of tokens to mint Must be executed in `MintPhase.INACTIVE` (i.e., before allowlist or public mint begins)/ | function ownerMint(uint256 _quantity) external onlyOwner inMintPhase(MintPhase.INACTIVE) {
require(totalSupply() + _quantity <= collectionSize, "insufficient supply");
_safeMint(owner(), _quantity);
}
| 2,677,021 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.